LeetCode-5 Longest Palindromic Substring(求最长回文子串)
2015-04-16 23:32
561 查看
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.
J***A:
Runtime:245 ms
分析:
两种情况分开处理,分别是回文数为奇数个、回文数为偶数个的情况(因为二者判定条件不同,具体参考我上面的代码)。
比较要留意的是两种情况的substring位置的考虑。
one unique longest palindromic substring.
J***A:
public class Solution { public static String longestPalindrome(String s) { String s1 = ""; String s2 = ""; int max = 0; int temp = 0; int iflag = 0; for (int i = 0; i < s.length(); i++) { //回文数为奇数个的情况。 for (int j = 1; i - j >= 0 && i + j <= s.length() - 1; j++) { if (s.charAt(i + j) == s.charAt(i - j)) temp++; else { break; } } if (temp > max) { max = temp; iflag = i; } temp = 0; } s1 = s.substring(iflag - max, iflag + max +1); max = 0; temp = 0; iflag = 0; for (int i = 0; i < s.length(); i++) { // 回文数为偶数个的情况。 for (int j = 0; i - j >= 0 && i + j + 1 <= s.length() - 1; j++) { if (s.charAt(i - j) == s.charAt(i + j + 1)) temp++; else { break; } } if (temp > max) { max = temp; iflag = i; } temp = 0; } s2 = s.substring(iflag - max +1, iflag + max +1); return s1.length()>s2.length()?s1:s2;//返回二者中更长的一个。 } }
Runtime:245 ms
分析:
两种情况分开处理,分别是回文数为奇数个、回文数为偶数个的情况(因为二者判定条件不同,具体参考我上面的代码)。
比较要留意的是两种情况的substring位置的考虑。
相关文章推荐
- leetcode (5) - Longest Palindromic Substring 最长回文子串
- Leetcode: 5 Longest Palindromic Substring 最长回文子串
- LeetCode 5. Longest Palindromic Substring(最长回文连续子串)
- LeetCode:Longest Palindromic Substring 最长回文子串
- LeetCode-Longest Palindromic Substring-最长回文子串-Manacher
- LeetCode:5_Longest Palindromic Substring | 最长的回文子串 | Medium
- 求最长回文子串 - leetcode 5. Longest Palindromic Substring
- LeetCode Longest Palindromic Substring 最长回文子串
- Longest Palindromic Substring [LeetCode] 最长回文子串
- [Leetcode] Longest palindromic substring 最长回文子串
- Longest Palindromic Substring 在一个字符串里找最长回文子串@LeetCode
- [C++]LeetCode: 99 Longest Palindromic Substring (最长回文子串)
- LeetCode OJ-5.Longest Palindromic Substring(最长回文子串)
- LeetCode_5---Longest Palindromic Substring (求最长回文子串)
- 【LeetCode刷题】最长回文子串Longest Palindromic Substring(java)
- LeetCode题库解答与分析——#5.最长回文子串LongestPalindromicSubstring
- LeetCode-5-Longest Palindromic Substring 最长回文子串DP
- leetcode--Longest Palindromic Substring--最长回文子串--
- LeetCode 5 Longest Palindromic Substring(最长回文子串,暴力剪枝/DP/曼彻斯特算法)
- LeetCode 5. Longest Palindromic Substring(最长回文子串)