LeetCode#5 Longest Palindromic Substring (week3)

来源:互联网 发布:mac中取消隐藏文件 编辑:程序博客网 时间:2024/06/06 23:27

week3

题目

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,找出其最长的回文串。解题思路大致为用一个字符串记录当前找到的最大的回文串,以s的每个字符作为回文串的中轴,向两边扩展得到以该字符作为中轴的最长字符串,并与记录的最长字符串比较长度决定是否替换。
在本题具体解题过程中我将以单独一个字符作为中轴及以两个字符作为中轴独立为Odd及Even两个类中的一个方法。

代码

/*检索一个字符串s中以两个字符作为中轴的最长回文串*/class Even {public:    string longestEvenString(string s) {        string result = "";        for (int i = 0; i < s.size(); ++i)        {            bool doWhile = false;            int j = i + 1;            int k = i;            if (j < s.size())            {                while (s[k] == s[j])                {                    doWhile = true;  /*进入while循环说明可以找到中轴*/                    if ((k - 1 < 0) || (j + 1 > s.size() - 1)) /*检索已到达字符串头部或尾部,停止检索*/                    {                        k--;                        j++;                        break;                    }                    else                    {                        k--;                        j++;                    }                }            }            string temp = "";            if (doWhile)            {                k++;                j--;                temp = s.substr(k, j - k + 1);            }            else            {                /*没有进入while循环,说明在此位置不存在以两个相同字符作为中轴的回文串*/                temp = "";            }            if (temp.size() > result.size()) /*得到新的最长的回文串*/            {                result = temp;            }        }        return result;    }};/*检索一个字符串s中以单独一个字符作为中轴的最长回文串*/class Odd {public:    string longestOddString(string s) {        string result = "";        for (int i = 0; i < s.size(); ++i)        {            /*j记录当前检索的位置的中轴偏移量*/            int j = 0;            while ((i - j >= 0) && ((i + j) <= (s.size() - 1))) /*检索已到达字符串头部或尾部,停止检索*/            {                if (s[i - j] == s[i + j])                {                    j++;                }                else {                    break;                }            }            j--;            string temp = s.substr(i - j, 2 * j + 1);            if (temp.size() > result.size()) /*得到新的最长的回文串*/            {                result = temp;            }        }        return result;    }};class Solution {public:    string longestPalindrome(string s) {        Odd O;        Even E;        string temp1 = O.longestOddString(s);        string temp2 = E.longestEvenString(s);        if (temp1.size() > temp2.size())        {            return temp1;        }        else        {            return temp2;        }    }};
原创粉丝点击