php - 如何按顺序查找特定字符的出现次数
问题描述
我试图在一组字符中查找特定字符串的出现次数。字符串中的字母不必相邻,但必须按顺序出现。
例如,以下序列包含四次出现的字符串“abc”
序列“aabcc”
出现:
a a b c c
a a b c c
a a b c c
a a b c c
有关如何在不消耗字符的情况下进行匹配的任何帮助?我试图使用正则表达式和匹配,但我不确定它是否可能。我正在为 php 写这个
解决方案
<?php
$sequence = "aabbcc";
$occurrences = array();
$sequences = str_split($sequence);
// dn($sequences);
$sequences_amount = array();
foreach ($sequences as $key => $char) {
if(!isset($sequences_amount[$char])){
$sequences_amount[$char] = 1;
}else{
$sequences_amount[$char]++;
}
}
var_dump($sequences_amount);
function sequenceCount($data = array())
{
if(!isset($data) || empty($data) || (count($data) == 0))return;
$count = NULL;
foreach ($data as $char => $amount) {
if($count == NULL){
$count = $amount;
}else{
$count = $count * $amount;
}
}
return $count;
}
$count = sequenceCount($sequences_amount);
echo("\n\nResult:\n");
echo($count);
推荐阅读
- java - 在没有 AbstractSecurityWebApplicationInitializer 的情况下启用 Spring Security
- oracle - 在 Oracle 中重建包后 webLogic 12c 中频繁出现 ORA-4068 错误
- c# - 加号在 nopcommerce 41 中转换为 + 但解析为 42beta
- r - 如何在 Rmarkdown 中注册用户输入后暂停
- powershell - Powershell参数、验证和定位
- c# - 从 PowerShell 检索 GetExecutingRequests 到 c# 对象
- javascript - 如何在 TypeScript 中使用泛型模拟 Java getClass()?
- java - Gson.fromJson(String, Class) 是如何工作的?
- continuous-integration - 使用 Gitlab API 和 CI 创建提交
- loops - OpenMP 问题:fortran 中的嵌套循环