5. Longest Palindromic Substring

来源:互联网 发布:数据魔方为什么下线 编辑:程序博客网 时间:2024/06/15 16:57

Description:

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"
 

思路分析:首先应该可以想到的方法是通过逐一比较的方式去解决问题。遍历字符串当中的每一个元素,并以当前元素为中心,寻找最长的回文字符串。但是应当注意的问题是回文的形式是有两种的,一种是“aba”形式的,另一种则是“bb”形式的,一定要在开始的时候就进行判断。

class Solution {public:    string longestPalindrome(string s) {        int startIdx = 0, left = 0, right = 0, len = 0;        for (int i = 0; i < s.size() - 1; ++i) {            if (s[i] == s[i + 1]) {                left = i;                right = i + 1;                searchPalindrome(s, left, right, startIdx, len);            }            left = right = i;            searchPalindrome(s, left, right, startIdx, len);        }        if (len == 0) len = s.size();        return s.substr(startIdx, len);    }    void searchPalindrome(string s, int left, int right, int &startIdx, int &len) {        int step = 1;        while ((left - step) >= 0 && (right + step) < s.size()) {            if (s[left - step] != s[right + step]) break;            ++step;        }        int wide = right - left + 2 * step - 1;        if (len < wide) {            len = wide;            startIdx = left - step + 1;        }    }};

第二种方法当时我是没有想到的,后来在网上看到别人有说可以通过动态规划的方法去实现,而且代码比较简单。然后我大致地看了一下,他是利用一个bool类型的二维数组去记录两两元素之间的关系。比如说它先判断了相邻的两个元素是否相同,并在二维数组当中记录;随后再次判断间隔距离为1的,然后步长逐步加大。感觉这种有点难以理解,不过为了方便学习也在这里贴出来。。

//动态规划算法  string longestPalindromeDP(string s) {    int n = s.length();    int longestBegin = 0;    int maxLen = 1;    bool table[1000][1000] = {false};    for (int i = 0; i < n; i++) {      table[i][i] = true;    }    for (int i = 0; i < n-1; i++) {      if (s[i] == s[i+1]) {        table[i][i+1] = true;        longestBegin = i;        maxLen = 2;      }    }    for (int len = 3; len <= n; len++) {      for (int i = 0; i < n-len+1; i++) {        int j = i+len-1;        if (s[i] == s[j] && table[i+1][j-1]) {          table[i][j] = true;          longestBegin = i;          maxLen = len;        }      }    }    return s.substr(longestBegin, maxLen);  }


0 0