classSolution{ public String longestPalindrome(String s){ int len = s.length(); int maxLen = 1; int begin = 0; char[] charArr = s.toCharArray(); for (int i = 0; i < len - 1; ++i) { for (int j = i + 1; j < len; ++j) { if(j - i + 1 > maxLen && isPalindrome(charArr, i, j)) { maxLen = j - i + 1; begin = i; } } } return s.substring(begin, begin + maxLen); } privatebooleanisPalindrome(char[] charArr, int i, int j){ while (i < j) { if (charArr[i] != charArr[j]) returnfalse; i++; j--; } returntrue; } }
// Using global variables will cause inconsistent result between "Run" and "Submit" funclongestPalindrome(s string)string { var size, maxLen, begin int = len(s), 1, 0 for i := 0; i < size - 1; i++ { begin, maxLen = isPalindrome(s, i, i, begin, maxLen) begin, maxLen = isPalindrome(s, i, i + 1, begin, maxLen) } return s[begin: begin + maxLen] }
funcisPalindrome(s string, i, j, begin, maxLen int)(int, int) { size := len(s) for i >= 0 && j < size && s[i] == s[j] { i-- j++ } if j - i - 1 > maxLen { begin = i + 1 maxLen = j - i - 1 } return begin, maxLen }
funclongestPalindrome(s string)string { var maxLen, begin, maxRight, center int = 1, 0, 0, 0 tmp := make([]rune, 0) tmp = append(tmp, '#') for _, c := range s { tmp = append(tmp, c) tmp = append(tmp, '#') } tsize := len(tmp) dp := make([]int, tsize) for i := 0; i < tsize; i++ { if i < maxRight { mirror := 2 * center - i; dp[i] = min(maxRight - i, dp[mirror]) } left, right := i - (dp[i] + 1), i + (dp[i] + 1) for left >= 0 && right < tsize && tmp[left] == tmp[right] { dp[i]++ left-- right++ } if i + dp[i] > maxRight { center, maxRight = i, dp[i] + i } if dp[i] > maxLen { maxLen = dp[i] begin = (i - maxLen) / 2 } } return s[begin: begin + maxLen] }
funcmin(x, y int)int { if x < y { return x } return y }