【php】php解决“最长回文子串” 2021.05.16 周日

1.题目

https://leetcode-cn.com/problems/longest-palindromic-substring/
leetcode 5: 最长回文子串
给你一个字符串 s,找到 s 中最长的回文子串。

1.解题思路

1)思路如下:
==回文子串的判断是:正序反序一样
== 暴力循环求解,可以优化的地方,后边不含有当前字符串,直接进行下一个字符串。
== 借助php的函数,反转函数: strrev(); 截取函数: substr($nowString, $fromIndex, $subLength), 注意长度不要写错了;是否含有字符串的函数 strpos()
== 还有就是回文子串一定有,至少是他自己

2.代码

class Solution {

    /**
     * @param String $s
     * @return String
     */
    function longestPalindrome($s) {
        if("" == $s){
            return "";
        }

        $length = strlen($s);
        // 目前最大的字符串
        $currentLongest = "";
        for($i = 0; $i < $length; $i++){
            $now = $s[$i];
            $sLeft = substr($s, $i + 1, $length - $i - 1);
            //var_dump("===01 i: $i", $sLeft, $s, $now, "\n");
            
            if(false === strpos($sLeft, $now)){
                continue;
            }
            // 得到匹配字符的数组
            $nextArray = $this->getMatchArr($sLeft, $now);
           // var_dump("====02 i: $i", $sLeft, $s, $now, $nextArray, "\n");
            
            foreach($nextArray as $index){
                //var_dump("s", $s, $i, $index);
                $nowStr = substr($s, $i, $index + 2);
                //var_dump("nowStr", $nowStr);
                // 不是最长回文子串则过滤
                if(false == $this->isHuiwenStr($nowStr) || strlen($nowStr) <= strlen($currentLongest)){
                    continue;
                }
                //var_dump("===03 i: $i", $currentLongest, $nowStr, "\n"); 
                $currentLongest = $nowStr;
               

            }
        }
        $currentLongest = $currentLongest == "" ? $s[0] : $currentLongest;
        return $currentLongest;
    }


    // 判断是否是回文子串
    function isHuiwenStr($str){
        
        if($str == strrev($str)){
            return true;
        }
        return false;
    }

    // 获取 字符$char在 $string中的位置:是一个数组
    function getMatchArr($string, $char){
        $resIndexs = array();
        //$stringArray = explode("", $string);
        //var_dump("stringArray", $stringArray, $string, $char);exit;
        //foreach($stringArray as $index=>$strChar){
          //  if($char == $strChar){
              //  $resIndexs[] = $index;
            //}
        //}

        $index = 0;
        $length = strlen($string);
        while(true){
            if($index >= $length)
            {
                break;
            }
            if($char == $string[$index]){
                $resIndexs[] = $index;
            }
            $index++;
        }
        return $resIndexs;          
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值