首页 > 解决方案 > 这个回文函数的复杂度是多少?

问题描述

<?php

    function p($s){
    $count = strlen($s);
    $start = 0;
    $end = $count-1;
        $r = true;
        while($start<$end){ 
            if(!isChar($s[$start])){
                $start++;
            }
            elseif(!isChar($s[$end])){
                $end--;
            }else{
                if($s[$start] !== $s[$end]){
                    $r = false;
                    break;
                }
                $start++;
                $end--;
            }
        }
        return $r;
    }


    function isChar($char){
        $char = strtolower($char);
        if (preg_match('/[a-z]/', $char)) {
         return TRUE;
        }
    }


    print_r(p("23123123!!,,we2ew")); // return true
?>

大家好,我写了一个函数,检查字符串是否是回文。字符串可以包含任何字符、数字和符号,但我需要在 az chars 中进行检查

123ebc123 - 假 ,<>ebbe - 真 123/.~!!aaa - 真

这是实现此功能的最有效方法吗?

ps不要看isChar函数实现,想象一下如果char是字母,只有一个函数返回true或false

谢谢

标签: palindrome

解决方案


如果我们使用 Big Oh 表示法来表示算法的时间复杂度,它将是 O(n)


推荐阅读