Longest Palindromic Substring [LeetCode]

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

Summary: line 18, reduce unneccessary search

 1     bool isPalindrome(string &s, int start, int end){
 2         while(start < end){
 3             if(s[start] != s[end])
 4                 return false;
 5             start ++;
 6             end --;
 7         }
 8         return true;
 9     }
10     
11     string longestPalindrome(string s) {
12         int longest = 0;
13         int start = 0;
14         int end = 0;
15         for(int i = 0; i < s.size(); i ++){
16             //find s[i] from end of S
17             for(int j = s.size() - 1; j >= i; j --){
18                 if(j - i + 1 <= longest)
19                     break;
20                 if(isPalindrome(s, i, j)){
21                     if(j - i + 1 > longest){
22                         longest = j - i + 1;
23                         start = i;
24                         end = j;
25                     }
26                     break;
27                 }
28             }
29         }
30         return s.substr(start, longest);
31     }

 

posted @ 2013-12-05 13:47  假日笛声  阅读(367)  评论(0编辑  收藏  举报