LongestPalindromicSubstring.java /** * 5. Longest Palindromic Substring * Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. * Example: * Input: "babad" * Output: "bab" * Note
/** * 5. Longest Palindromic Substring * Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. * Example: * Input: "babad" * Output: "bab" * Note: "aba" is also a valid answer. * Input: "cbbd" * Output: "bb" * @param s * @return */ public static String longestPalindrome(String s) { if (s.length() == 1) { return s; } if (s.length() == 2) { return s.charAt(0) == s.charAt(1) ? s : ""; } String resultString = ""; for (int i = 0; i < s.length(); i++) { for (int j = i + 1; j < s.length(); j++) { String tmp = s.substring(i, j+1); if(tmp.equals(reverse(tmp)) && tmp.length()>= resultString.length()){ resultString = tmp; } } } return resultString; } private static String reverse(String s){ StringBuffer strBuffer = new StringBuffer(); for(int i=s.length()-1;i>=0;i--){ strBuffer.append(s.charAt(i)); } return strBuffer.toString(); }