简体   繁体   中英

How do I reduce time complexity of this substring palindrome?

I am solving this problem, input: a string, output: it's longest substring that is a palindrome I solved it in the below manner in O(n^3). I am trying to solve it in O(n^2). Please help. Here is the code:

int isPalindrome(string str){
    for(int i = 0, j = str.size()-1 ; i < j ;i++,j--){
        if(str[i] != str[j])
            return 1; //1 is the minimal palindrome length
    }
    return str.size();// return length of palindrome
}

string longestPalindromicSubstring(string str) {

    int maxLength = 0;
    string result = "";
    
    for(int i = 0; i < str.size(); i++){ 
            for(int j = 1; j <= str.size(); j++){ 
                string temp = str.substr(i,j); //substring of length j

                if(temp.size() > maxLength){
                  int count = isPalindrome(temp);
                    if(count>maxLength){
                        maxLength = count;
                        result = temp; //saving the substring as result
                    }
                }
            }// j for loop ends
    } //i loop ends
    
  return result;
}
pair<int,int> getPalindromeRange(string str, int left, int right){
    while(left>=0 && right<str.length()){
        if(str[left] != str[right]) 
            break;
        left--;
        right++;
    }
    return make_pair(left+1, right);
}


string longestPalindromicSubstring(string str) {

    pair<int,int>longestRange{0,1};//first value is starting index and second value is the length of the substring
    
    string result ="";

    for(int i=1 ;i<str.length(); i++){
        pair<int,int>odd = getPalindromeRange(str, i-1, i+1);
        pair<int,int>even = getPalindromeRange(str, i-1, i);
        
        if(longestRange.second - longestRange.first < odd.second - odd.first)
            longestRange = odd;
        
        if(longestRange.second - longestRange.first < even.second - even.first)
            longestRange = even;

        if (longestRange.second - longestRange.first == str.length())
            break;
        
    }//for loop ends
    result = str.substr(longestRange.first, longestRange.second -longestRange.first);
    
  return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM