首页 > 解决方案 > 如何按顺序查找特定字符的出现次数

问题描述

我试图在一组字符中查找特定字符串的出现次数。字符串中的字母不必相邻,但必须按顺序出现。

例如,以下序列包含四次出现的字符串“abc”

序列“aabcc”

出现:

a a b c c

a a b c c

a a b c c

a a b c c

有关如何在不消耗字符的情况下进行匹配的任何帮助?我试图使用正则表达式和匹配,但我不确定它是否可能。我正在为 php 写这个

标签: phpregex

解决方案


演示

<?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);

推荐阅读