• Longest Palindromic Substring(字符串的最大回文子串)


    题目描述:
    Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
    意思是给出一个字符串s,找出其中长度最大的回文子串。
    思路:
    回文串的对称点开始,依次向左向右比较,不相同的时候停止遍历,直到遍历完字符串s,同时找出最大的长度的回文子串
    特别注意的是,“对称点”有两种可能,一种就是某个特定位置的字符,此时回文串的长度为奇数,另一种就是两个字符的中间位置,此时回文串长度为偶数,需要进行特殊判断。
    (1)回文子串长度为奇数:对称点只有一个字符
    (2)回文子串长度为偶数:对称点有两个字符
    时间复杂度为O(n^2): 对称点的数量为O(n),每次查找的时间复杂度也是O(n),所以最后的总复杂度为O(n^2)

    代码:

    /**思路:
    *    回文串的对称点开始,依次向左向右比较,不相同的时候停止遍历,直到遍历完字符串s,同时找出最大的长度的回文子串
    *    回文子串长度为奇数:对称点只有一个字符
    *    回文子串长度为偶数:对称点有两个字符
    */
    class Solution {
    public:
        string longestPalindrome(string s) {
            //字符串的长度
            int len = s.size();
            if (len == 0) return s;
            //保留最长回文串
            string resultStr = "";
            //回文子串长度为奇数,:对称点只有一个字符的情况
            for (int i=0; i<len; ++i){
                // i 为对称点
                int left = i;//左
                int right = i;//右
                //向左向右遍历,直到发现不相同的时候停止
                while (left > 0 && right < len - 1 && s[left - 1] == s[right + 1]){
                    --left;
                    ++right;
                }
                //比较,更新最长回文串
                if (right - left + 1 > resultStr.size()){
                    resultStr = s.substr(left, right - left + 1);
                }
            }
    
            //回文子串长度为偶数:对称点有两个字符
            for (int i = 0; i < len - 1; ++i){
                if (s[i] == s[i+1]){//两个对称点相同,才有继续遍历的意义
                    int left = i;
                    int right = i+1;
                    //向左向右遍历,直到发现不相同的时候停止
                    while (left > 0 && right < len - 1 && s[left - 1] == s[right + 1]){
                        --left;
                        ++right;
                    }
                    //比较,更新最长回文串
                    if (right - left + 1 > resultStr.size()){
                        resultStr = s.substr(left, right - left + 1);
                    }
                }
            }
            return resultStr;
        }
    };
    不积跬步,无以至千里;不积小流,无以成江海。
  • 相关阅读:
    使用Link Shell Extension方便的创建同步文件
    DOM案例【3】密码强度检查案例
    DOM案例【2】注册文本倒计时
    DOM案例【1】文本时钟
    HTML5 and CSS【01】Font
    常用单词
    CSS基础【01】类和ID选择器的区别
    【03】Html重点
    【02】Html(如鹏)
    C#MD5计算代码
  • 原文地址:https://www.cnblogs.com/xiaocai-ios/p/7779792.html
Copyright © 2020-2023  润新知