longest palindromic substring

 

Topic description

 

For a string, design an efficient algorithm to calculate the length of the longest palindrome substring.

Given a string A and its length n , return the length of the longest palindrome substring.

 
Test example:
 
"abc1234321ab",12

Returns
: 7

 

Problem solving ideas

 

Consider using the center expansion method, that is, traverse each character in turn to compare whether the characters on both sides are equal and record, there are two cases: the length of the substring is odd and even. The time complexity of the algorithm is O(N 2 )

 

code

 

 1 class Palindrome {
 2 public:
 3     int getLongestPalindrome(string str, int n) {
 4         int count = 0;  
 5         int max = 0; 
 6         if (str.empty() || n<1)
 7             return 0;
 8         for(int i=0;i<n;i++){
 9             for(int j=0;i+j<n&&i-j>=0;j++){
10                 if(str[i-j]!=str[i+j])
11                     break;
12                 count=j*2+1;
13             }
14             if(count>max)
15                 max=count;
16             for(int j=0;i+j+1<n&&i-j>=0;j++){
17                 if(str[i-j]!=str[i+j+1])
18                     break;
19                 count=j*2+2;
20             }
21             if(count>max)
22                 max=count;
23         }
24         return max;  
25     }
26 };

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325018402&siteId=291194637