标签:one HERE panda 解答 int and The expand 复杂
题目:
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 public class Solution { 2 3 public String longestPalindrome(String s) { 4 int start = 0; 5 int end = 0; 6 7 8 //对于找回文字串的问题,就要以每一个字符为中心,像两边扩散来寻找回文串 9 //这个算法的时间复杂度是O(n*n),可以通过OJ 10 //就是要注意奇偶情况,由于回文串的长度可奇可偶,比如"bob"是奇数形式的回文,"noon"就是偶数形式的回文,两种形式的回文都要搜索,对于奇数形式的,我们就从遍历到的位置为中心,向两边进行扩散,对于偶数情况,我们就把当前位置和下一个位置当作偶数行回文的最中间两个字符,然后向两边进行搜索 11 for(int i = 0; i < s.length(); i++) { 12 int len1 = expandAroundCenter(s, i, i); 13 int len2 = expandAroundCenter(s, i, i+1); 14 int len = Math.max(len1, len2); 15 if(len > end - start) { 16 start = i - (len - 1) / 2; 17 end = i + len / 2; 18 } 19 } 20 21 return s.substring(start, end+1); 22 } 23 24 private int expandAroundCenter(String s, int left, int right) { 25 int L = left; 26 int R = right; 27 while(L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) { 28 L--; 29 R++; 30 } 31 32 return R-L-1; 33 } 34 }
标签:one HERE panda 解答 int and The expand 复杂
原文地址:https://www.cnblogs.com/wylwyl/p/10397128.html