Leetcode 005 Longest Palindromic Substring

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Gongzq5/article/details/81255485

Leetcode 005 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”


Solution

class Solution {
public:
    string longestPalindrome(string s) {
        // Dynamic Programming
        // abcb
        int maxLen = 0;
        int maxS = 0, maxE = 0;
        int len = s.length();
        for (int i = 0; i < len; ++i) {
            // 选取s[i]为中心,不断扩展
            // cerr << "\n\n-----------" << i << " is middle.-----------\n" << endl;
            int start = i-1, end = i+1;
            while (start >= 0 && end < len) {
                // cout << "check " << start << " " << end << endl;
                if (s[start] == s[end]) {
                    // cout << "check pass.\n"; 
                    start--; end++;
                } else {
                    // cout << "check not pass\n";
                    break;
                }
            }
            if (!(start >= 0 && end < len)) {
                // cout << "loop condition not satisfy.\n";
            }
            if (end - start - 1 > maxLen) {
                maxS = start + 1; maxE = end - 1;
                maxLen = maxE - maxS + 1;
                // cout << "replace with " << maxS << " " << maxE << "\n";
            }


            // cout << "------use another function------\n";
            start = i, end = i+1;
            while (start >= 0 && end < len) {
                // cout << "check " << start << " " << end << endl;
                if (s[start] == s[end]) {
                    // cout << "check pass.\n"; 
                    start--; end++;
                } else {
                    // cout << "check not pass\n";
                    break;
                }
            }
            if (!(start >= 0 && end < len)) {
                // cout << "loop condition not satisfy.\n";
            }
            if (end - start - 1 > maxLen) {
                maxS = start + 1; maxE = end - 1;
                maxLen = maxE - maxS + 1;
                // cout << "replace with " << maxS << " " << maxE << "\n";
            }
        }
        return s.substr(maxS, maxLen);
    }
};

注释掉的内容是DEBUG时候用的,对于代码的运行情况可以看得很明白,可以解开注释试试看。

分析

大概的思路是这样

  1. 以一个字符为中心(s[i]),往两边扩展,如果两边的字符相等(s[i-1]以及s[i+1]),那么扩展后的字符串就是个回文串;
  2. 选择字符串中的每一个字符,依次按照 1 中的步骤进行扩展直到不是回文串为止,此时记录下来当前的记录;
  3. 按照 1 中的步骤只能处理类似于"aba"这样的回文字符串,除此以外我们还有"bb"这样的回文字符串。此时我们要换一种方式,不以什么字符为中心,而是直接判断s[i]s[i+1],以此进行扩展。

总体来说效率还是蛮高的,我也没有写暴力破解的方案,按照官方的solution,暴力破解的时间复杂度是 O ( n ) ;而这个方案的复杂度大致是介于 O ( n ) O ( n 2 ) 之间(for循环进行n次,内部while循环进行不超过n/2次)。

猜你喜欢

转载自blog.csdn.net/Gongzq5/article/details/81255485