xinyu04

导航

LeetCode 5 Longest Palindromic Substring

Given a string s, return the longest palindromic substring in s.

Solution

求在 \(s\) 中的最长回文字串。对于每一个位置,进行左右拓展,计算出长度并更新答案即可。

\(Notes:\) 对于奇数或者偶数长度的字串,为了统一:

  • 奇数: \(check(s,i,i)\)
  • 偶数:\(check(s,i,i+1)\)
点击查看代码
class Solution {
private:
    string ans="";
    
    string check(string& s, int l,int r){
        while(l>=0 && r<s.length() && s[l]==s[r]){
            l--;r++;
        }
        // [l+1, r-1]
        return s.substr(l+1, r-l-1);
    }
    
public:
    string longestPalindrome(string s) {
        for(int i=0;i<s.length();i++){
            string ans1 = check(s, i, i);
            string ans2 = check(s, i, i+1);
            string cd = ans1.size()>ans2.size()?ans1:ans2;
            ans = ans.size()>cd.size()?ans:cd;
        }
        return ans;
    }
};

posted on 2022-08-11 02:40  Blackzxy  阅读(11)  评论(0编辑  收藏  举报