Question: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.(给定一个字符串S,在S中找到最长的回文子字符串,假定最长的回文字符串长度是1000,并且在这个字符串中存在唯一的一个最长回文子字符串)
今天做到leetcode上的这个题,没有想到这个题也竟然是百度14年的笔试题,题目大体相同。下面我来分享一下我在做这个题的时候的一些感悟。
最开始,对这个题没有思路,想到一种很笨的方法,也就是穷举的思想,能够得到最长的回文子字符串,但是leetcode测试时间超时,下面是这种方法的代码(Java)
1 class Solution { 2 //超过leetcode时间要求 3 public String longestPalindrome(String s) { 4 // Note: The Solution object is instantiated only once and is reused by each test case 5 String str=new String(); 6 int max=0; 7 //穷举法是很笨的方法 8 for(int i=0;i<s.length();i++){ 9 for(int j=i+2;j<=s.length();j++){ 10 if(isPalindrome(s.substring(i,j))&&(j-i)>max){ 11 str=s.substring(i,j); 12 max=j-i; 13 } 14 } 15 } 16 return str; 17 } 18 //判断是否是回文字符串 19 public Boolean isPalindrome(String s){ 20 for(int i=0;i<s.length()/2;i++){ 21 if(s.charAt(i)!=s.charAt(s.length()-i-1)) 22 return false; 23 } 24 return true; 25 } 26 }