• [leetcode] 5. 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.

    Example:

    Input: "babad"
    
    Output: "bab"
    
    Note: "aba" is also a valid answer.

    Example:

    Input: "cbbd"
    
    Output: "bb"


    思路很简单:遍历字符串,找出以每个字符为中间字符的最长的回文串,再次遍历字符,找出以两个重复字符为中间字符的最长的字符串,从而得到字符串 s 的最长回文子串。

    以下是我的代码,其中再确认中间字符时寻找最长回文串的代码重复了两次,也可以独立出一个函数来调用:
    class Solution {
    public:
        string longestPalindrome(string s) {
            int pos = 0, left = 0, right = 0, len = s.size();
            string result = "";
            while (pos < len) {
                while (1) {
                    if (s[left] != s[right]) break;
                    string tmp = s.substr(left, right - left + 1);
                    if (tmp.size() > result.size()) result = tmp;
                    if (--left < 0) break;
                    if (++right >= len) break;
                }
                pos++;
                left = pos, right = pos;
            }
            for (int i = 0; i < len - 1; i++) {
                if (s[i] == s[i+1]) {
                    left = i, right = i+1;
                    while (1) {
                        if (s[left] != s[right]) break;
                        string tmp = s.substr(left, right - left + 1);
                        if (tmp.size() > result.size()) result = tmp;
                        if (--left < 0) break;
                        if (++right >= len) break;
                    }
                }
            }
            return result;
        }
    };



  • 相关阅读:
    2019牛客暑期多校训练营(第三场)B题、H题
    2019牛客暑期多校训练营(第四场)k题、j题
    Manacher算法 & Palindrome
    HDU 3336——Count the string
    判断一个点是否在三角形内
    P1052 过河
    P1353 [USACO08JAN]跑步Running
    hdu 1686 Oulipo
    Cyclic Nacklace HDU
    高精地图技术分析
  • 原文地址:https://www.cnblogs.com/zmj97/p/7651490.html
Copyright © 2020-2023  润新知