[LeetCode] Longest Palindromic Substring

来源:互联网 发布:求好玩的网络手机游戏 编辑:程序博客网 时间:2024/06/05 02:06

Iterate each character as the center, expand to two ends to find the longest palindromic string.

class Solution {public:    string longestPalindrome(string s) {        string result="";        for(int i=0;i<s.length();i++) {            string tmp=getLongest(s,i,i);   // odd #            if(result.length()<tmp.length())                result=tmp;            tmp=getLongest(s,i,i+1);        // even #            if(result.length()<tmp.length())                result=tmp;        }        return result;    }    string getLongest(string &s, int l, int r) {        while(l>=0 && r<s.length() && s[l]==s[r]) {            l--; r++;        }        return s.substr(l+1,r-l-1);    }};


0 0