• 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 1:
    Input: "babad"
    Output: "bab"
    Note: "aba" is also a valid answer.

    Example 2:
    Input: "cbbd"
    Output: "bb"

    class Solution {
    public:
        string longestPalindrome(string s) {
        if (s.empty()) return "";
        if (s.size() == 1) return s;
        int min_start = 0, max_len = 1;
        for (int i = 0; i < s.size();) {
          if (s.size() - i <= max_len/2) break;
          int j = i, k = i;
          while (k < s.size()-1 && s[k+1] == s[k]) ++k; // Skip duplicate characters.
          i = k+1;
          while (k < s.size()-1 && j > 0 && s[k + 1] == s[j - 1]) { ++k; --j; } // Expand.
          int new_len = k - j + 1;
          if (new_len > max_len) { min_start = j; max_len = new_len; }
        }
        return s.substr(min_start, max_len);
    }
    };
    /*
    string longestPalindrome(string s) {
            if(s.size()==0) return s;
            int res = 1;
            string ans = s.substr(0, 1);
            vector<vector<int>> dp(s.size(), vector<int>(s.size(), 0));
            for(int i=0; i<s.size(); i++){
                dp[i][i] = 1;
                if( i < s.size()-1 && s[i] == s[i+1]){
                    dp[i][i+1] = 1;
                    ans = s.substr(i, 2);
                }       
            }
            for(int len = 3; len <= s.size(); len++)
                for(int i=0; i<= s.size()-len; i++)
                    if(dp[i+1][i+len-2]==1 && s[i]==s[i+len-1]){
                        dp[i][i+len-1] = 1;
                        ans = s.substr(i, len);
                    }
            return ans;
        }
    */
    
  • 相关阅读:
    promise的终止调用方法:
    (五)浅谈测试用例
    (四)一个bug的生命周期
    (三)趣谈软件需求分析
    (二)软件测试分类
    (一) 软件测试实质
    【转载—“光荣之路”公众号】Bug预防体系(上千bug分析后总结的最佳实践)
    <MFC>FILE的操作
    <CAN>测试的原理
    <C++>消息循环
  • 原文地址:https://www.cnblogs.com/A-Little-Nut/p/10041074.html
Copyright © 2020-2023  润新知