题目链接:https://leetcode.com/problems/longest-palindromic-substring/description/
题目大意:找出最长回文子字符串(连续)。
法一:暴力,三层for循环,超时。代码如下:
1 public String longestPalindrome(String s) { 2 String res = ""; 3 //逐一检查每个子字符串 4 for(int i = 0; i < s.length(); i++) { 5 for(int j = i + 1; j < s.length(); j++) { 6 String tmp = s.substring(i, j + 1); 7 if(isPalindrome(tmp) == true) { 8 if(tmp.length() > res.length()) { 9 res = tmp; 10 } 11 } 12 } 13 } 14 if(res.length() == 0) { 15 res = String.valueOf(s.charAt(0)); 16 } 17 return res; 18 } 19 //判断子字符串是否是回文 20 public static boolean isPalindrome(String s) { 21 for(int i = 0, j = s.length() - 1; i < j; i++, j--) { 22 if(s.charAt(i) != s.charAt(j)) { 23 return false; 24 } 25 } 26 return true; 27 }