PHP计算字符串出现次数的最快方法是什么?

时间:2013-11-28 15:25:54

标签: php function

字符串S的前缀是S的任何前导连续部分。例如,“c”和“cod”是字符串“codility”的前缀。为简单起见,我们要求前缀非空。 字符串S的前缀P的乘积是P的出现次数乘以P的长度。更准确地说,如果前缀P由K个字符组成并且P在S中恰好出现T次,那么乘积等于K * T. 例如,S =“abababa”具有以下前缀:

"a", whose product equals 1 * 4 = 4,
"ab", whose product equals 2 * 3 = 6,
"aba", whose product equals 3 * 3 = 9,
"abab", whose product equals 4 * 2 = 8,
"ababa", whose product equals 5 * 2 = 10,
"ababab", whose product equals 6 * 1 = 6,
"abababa", whose product equals 7 * 1 = 7.

最长前缀与原始字符串相同。目标是选择这样的前缀以最大化产品的价值。在上面的例子中,最大乘积是10。 在这个问题中,我们只考虑由小写英文字母(a-z)组成的字符串。 写一个函数

class Solution { public int solution(String S); }

给定由N个字符组成的字符串S,返回给定字符串的任何前缀的最大乘积。如果产品大于1,000,000,000,则该功能应返回1,000,000,000。 例如,对于字符串:

S = "abababa" the function should return 10, as explained above,
S = "aaa" the function should return 4, as the product of the prefix "aa" is maximal.

假设:

N is an integer within the range [1..300,000];
string S consists only of lower-case letters (a−z).

复杂度:

expected worst-case time complexity is O(N);
expected worst-case space complexity is O(N) (not counting the storage required for input arguments).

到目前为止我的代码:

function solution($S) {
    $PROD = 0;
    for ($i=1; $i <= strlen($S); $i++){
        $p = substr($S, 0, $i);
        $counter = 0;
        $offset = 0;
        $pos = strpos($S, $p, $offset);
        while($pos !== false) { 
            $counter++;
            $offset = $pos + 1;            
            $pos = strpos($S, $p, $offset);
        }
        if ($PROD < ($counter * strlen($p))){
            $PROD = $counter * strlen($p);
            if ($PROD > 1000000000)
                return 1000000000;
        }
    }
    return $PROD;
}

有没有办法更快地完成它?

1 个答案:

答案 0 :(得分:1)

我认为你必须自己动手。我就是这样做的:

<强> The demo

function substr_count_overlap($string, $needle) {
    $count = 0;
    $start = 0;
    while(1) {
        $found = strpos($string, $needle, $start);
        if($found !== FALSE) {
            $count++;
            $start = $found + 1;
        } else return $count;
    }
    return $count;
}

并以这种方式使用它:

$myString = 'aaa';
$search = 'aa';

echo substr_count_overlap($myString, $search);

由于这一行,这个更快:

$start = $found + 1;

您不会将整个字符串1个字符串1逐行,但您可以直接进入下一个出现的位置。