LeetCode 147 Longest Palindromic Substring
2014-11-01 16:45
309 查看
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.
分析:
对于每一个位置,都向两边找对称的字串,更新最长对称字串。
注意,对称有两种情况,
1,aba的情况
2,abba的情况
public class Solution {
public String longestPalindrome(String s) {
if(s==null || s.isEmpty())
return null;
if(s.length()==1)
return s;
String longest = s.substring(0,1);
for(int i=0; i<s.length(); i++){
//有一个对称中心的情况,例如1,2,1的情况
String tmp = helper(s,i,i);
if(tmp.length() > longest.length())
longest = tmp;
//没有对称中心的情况,例如1,2,2,1的情况
tmp = helper(s,i,i+1);
if(tmp.length()>longest.length())
longest = tmp;
}
return longest;
}
public String helper(String s, int begin, int end){
while(begin>=0 && end<=s.length()-1 && s.charAt(begin)==s.charAt(end)){
begin--;
end++;
}
return s.substring(begin+1, end);
}
}
分析:
对于每一个位置,都向两边找对称的字串,更新最长对称字串。
注意,对称有两种情况,
1,aba的情况
2,abba的情况
public class Solution {
public String longestPalindrome(String s) {
if(s==null || s.isEmpty())
return null;
if(s.length()==1)
return s;
String longest = s.substring(0,1);
for(int i=0; i<s.length(); i++){
//有一个对称中心的情况,例如1,2,1的情况
String tmp = helper(s,i,i);
if(tmp.length() > longest.length())
longest = tmp;
//没有对称中心的情况,例如1,2,2,1的情况
tmp = helper(s,i,i+1);
if(tmp.length()>longest.length())
longest = tmp;
}
return longest;
}
public String helper(String s, int begin, int end){
while(begin>=0 && end<=s.length()-1 && s.charAt(begin)==s.charAt(end)){
begin--;
end++;
}
return s.substring(begin+1, end);
}
}
相关文章推荐
- [LeetCode]Longest Palindromic Substring
- [Leetcode]Longest Palindromic Substring
- leetcode--Longest Palindromic Substring
- LeetCode-Longest Palindromic Substring
- leetcode Longest Palindromic Substring
- leetcode[5]Longest Palindromic Substring
- LeetCode 5 Longest Palindromic Substring
- [LeetCode]05. Longest Palindromic Substring (动态规划)
- LeetCode 之 5 ---- Longest Palindromic Substring
- [LeetCode] Longest Palindromic Substring 解题报告
- Leetcode 5 Longest Palindromic Substring
- leetcode-Longest Palindromic Substring
- Longest Palindromic Substring leetcode java
- Leetcode Longest Palindromic Substring(最长回文字串)
- 【JAVA、C++】LeetCode 005 Longest Palindromic Substring
- [leetcode]Longest Palindromic Substring
- Leetcode:Longest Palindromic Substring
- [LeetCode] 5. Longest Palindromic Substring
- LeetCode:Longest Palindromic Substring
- [LeetCode] Longest Palindromic Substring [14]