leetcode brush diary title

 

   Here the main method used is the center of expansion, i.e. to traverse the entire string, because the center may be a single letter, it may be similar to the two-letter abbc such, it is necessary to discuss them Points:

    If a single letter is, when there are n case, if two letters, there was n-1 case. Therefore, in the case together it is 2n-1

    Next, each test was then extended center, and finally determined the longest palindromic sequence.

    Determine the position of its center of approximately beginning, and then subtracting substr function directly to obtain desired strings.

Codes are as follows:

 1 class Solution {
 2 public:
 3     int expandAroundCenter(string s, int left, int right)
 4     {
 5         int L=left, R=right;
 6         while(L>=0&&R<s.length()&&s[L]==s[R])
 7         {
 8             L--;
 9             R++;
10         }
11         return R-L-1;
12     }
13     
14     string longestPalindrome(string s) {
15         if(s.length() < 1)
16         {
17             return "";
18         }
19         int start =0,end =0;
20         for(int i = 0; i<s.length();i++)
21         {
22             int len1 = expandAroundCenter(s,i,i);
23             int len2 = expandAroundCenter(s,i,i+1);
24             int len = max(len1,len2);
25             if(len > end - start)
26             {
27                 start = i - (len-1)/2;
28                 end   =  i + (len)/2;
29             }
30         }return s.substr(start,end - start +1);
31     }
32     
33 };

Final time complexity is O (n ^ 2)

 

 

    

Guess you like

Origin www.cnblogs.com/xingzhuan/p/11466129.html