1 题目:
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.
String
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabcaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
时间超了,我也没想出其他的办法。
后来看这个帖子:https://leetcode.com/discuss/17622/optimized-n-square-solution-in-java
它是采用了贪心法。里面解释也很详细,不再说了。
自己动手敲了一遍,实现了。
public class Solution { public String longestPalindrome(String s){ int end = s.length() - 1; int length = end + 1; String longestSubString = ""; for (int i = 0; i < length; i++) { int start = i; int rear = end; int temp = rear; while( start < rear ){ if (s.charAt(start) == s.charAt(rear)) { start++; rear--; }else { start = i; temp--; rear = temp; } if (start >= rear) {//结束了 if (longestSubString.length() < s.substring(i, temp + 1).length()) { longestSubString = s.substring(i, temp+1); } if(longestSubString.length() == s.substring(i,end+1).length()){ return longestSubString; } } } } return longestSubString; } }
看懂别人代码后,自己实现的:
public class Solution { public String longestPalindrome(String s){ char[] chars = s.toCharArray(); int len = s.length(); while(len >= 0){ for(int i = 0; i + len - 1 < chars.length; i++){ int right = i; int left = i + len - 1; boolean isPalin = true; while(right <= left){ if(chars[right] == chars[left]){ right++; left--; continue; }else{ isPalin = false; break; } } if(isPalin){ return s.substring(i, i + len); } } len--; } return ""; } }