A method cost much time, easy to understand. can someone optimize it?


  • 0

    A method cost much time, easy to understand.

    class Solution {
    public:
        bool isPalindrome(string &s, int i, int j){ 
            while(i < j){
                if(s[i] != s[j])
                    return false;
                i++;
                j--;
            }
            return true;
        }
    
        string longestPalindrome(string s) {
            int left, length = 0;
            int strlen = s.size();
            int i, j, k;
    
            for(i = 0; i < strlen - length; i++){
                k = strlen - 1;
                while((j = s.rfind(s[i], k)) - i + 1 > length){ 
                    k = j - 1;
                    if(isPalindrome(s, i, j)){
                        left = i;
                        length = j - i + 1;
                        break;
                    }
                }
            }
            string substring = s.substr(left, length);
            return substring;
        }
    };
    

    It cost 99 ms.
    I think it can be optimized, can someone modified it?


Log in to reply
 

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