simple C++ code, 6ms


  • 1
    P
    class Solution {
    public:
        string longestPalindrome(string str) {
            str = "$" + str;
            int len = str.length();
            int ans = 1, start = 1, end = 1;
            int s, e, t;
            for(int i = 1; i < len; i++){
                s = i, e = i;
                while(str[e + 1] == str[i]) ++e;
                i = e;
                while(str[s - 1] == str[e + 1]) --s, ++e;
                if((t = e - s + 1) > ans){
                    start = s;
                    end = e;
                    ans = t;
                }
            }
            return str.substr(start, ans);
        }
    };
    

  • 0
    K

    It's a good solution,but still exists some problem.
    Testcase "aa$" fails.

        int len = str.length();
        int ans = 1, **start = 0, end = 0**;
        int s, e, t;
        for(**int i = 0**; i < len; i++){
            s = i, e = i;
            while(str[e + 1] == str[i]) ++e;
            i = e;
            **while(s-1>=0&&str[s - 1] == str[e + 1]) --s, ++e;**

  • 0
    P

    Oh, Thanks, This method need to add a character that never appeared, I choose the '$'. So I think this is the point.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.