leetcode:最长回文子串
2019-07-06 15:48
267 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_42451640/article/details/94863946
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
示例 1:
输入: “babad”
输出: “bab”
注意: “aba” 也是一个有效答案。
示例 2:
输入: “cbbd”
输出: “bb”
思路
1.最长回文串可能是奇数或者偶数长度
2.奇数长度的特点是:扫描当前字符的前一个和后一个字符如果相等,依次向2边蔓延开继续判断。
3.偶数长度的特点是:先扫描到2个相邻相同的字符作为判断的开始,依次向2边蔓延开继续判断。
4.边界问题:空字符串或者字符串长度为1返回字符串本身,初始化最长回文串为字符串的第一个字符
class Solution { public String longestPalindrome(String s) { if (s.length()==0||s.length()==1){ return s; } int maxIndex = 0; int maxLength = 1; if (s.charAt(0)==s.charAt(1)){ maxLength=2; } boolean flag; //标记是奇数还是偶数回文串 for (int i = 1; i < s.length() - 1; i++) { // 偶数长度的回文串 if (s.charAt(i) == s.charAt(i + 1)) { int strLength = 2; int strIndex = i; int j = i - 1; int k = i + 2; while (j >= 0 && k <= s.length() - 1) { if (s.charAt(j) == s.charAt(k)) { strLength += 2; j--; k++; } else { break; } } if (strLength > maxLength) { maxIndex = strIndex - strLength / 2 + 1; maxLength = strLength; flag = true; } } // 奇数回文串 if (s.charAt(i - 1) == s.charAt(i + 1)) { int strLength = 3; int strIndex = i; int j = i - 2; int k = i + 2; while (j>=0&&k<=s.length()-1){ if (s.charAt(j)==s.charAt(k)){ strLength+=2; j--; k++; }else{ break; } } if (strLength > maxLength) { maxIndex = strIndex - strLength / 2 ; maxLength = strLength; flag = false; } } } return s.substring(maxIndex, maxIndex + maxLength); } }
相关文章推荐
- [C++]LeetCode: 99 Longest Palindromic Substring (最长回文子串)
- LeetCode--5.最长回文子串(Longest Palindromic Substring)
- Leetcode 5. 最长回文子串
- LeetCode:Longest Palindromic Substring 最长回文子串
- leetcode 最长回文子串
- [C++]LeetCode 5: Longest Palindromic Substring(最长回文子串)
- 每天一道LeetCode-----最长回文子串/序列,从头开始的最长回文子串长度
- LeetCode——5. 最长回文子串
- Leetcode-最长回文子串
- leetcode第5题,最长回文子串
- [Leetcode] Longest palindromic substring 最长回文子串
- LeetCode | Longest Palindromic Substring(最长回文子串)
- 转载:LeetCode:5Longest Palindromic Substring 最长回文子串
- LeetCode 5. 最长回文子串
- LeetCode之“字符串”:最长回文子串
- 【Leetcode】5.最长回文子串
- LeetCode[5] 最长的回文子串
- LeetCode5. 最长回文子串(Java)
- 【 Javascript刷LeetCode系列】5. Longest Palindromic Substring 最长回文子串问题
- Leetcode 5 最长回文子串