1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| class Solution { public String longestPalindrome(String s) { int strlen = s.length(); if(s == null || strlen == 0) return ""; int left = 0, right = 0; int len = 1, maxStart = 0, maxLen = 0; for(int i = 0; i < strlen; i++){ left = i - 1; right = i + 1; while(left >= 0 && s.charAt(i) == s.charAt(left)){ left--; len++; } while(right < strlen && s.charAt(i) == s.charAt(right)){ right++; len++; } while(left >= 0 && right < strlen && s.charAt(left) == s.charAt(right)){ left--; right++; len += 2; } if(len > maxLen){ maxLen = len; maxStart = left; } len = 1; } return s.substring(maxStart + 1, maxStart + maxLen + 1); } }
class Solution { public String longestPalindrome(String s) { int strlen = s.length(); if(s == null || strlen < 2){ return s; }
int maxStart = 0, maxEnd = 0, maxLen = 1; boolean[][] dp = new boolean[strlen][strlen];
for(int r = 1; r < strlen; r++){ for(int l = 0; l < r; l++){ if(s.charAt(l) == s.charAt(r) && (r - l <= 2 || dp[l+1][r-1])){ dp[l][r] = true; if(r - l + 1 > maxLen){ maxLen = r - l + 1; maxStart = l; maxEnd = r; } } } } return s.substring(maxStart, maxEnd+1); } }
class Solution { public String longestPalindrome(String s) { String ans = ""; int max = 0; int len = s.length(); for(int i = 0; i < len; i++){ for(int j = i + 1; j <= len; j++){ String test = s.substring(i, j); if(isPalindrome(test) && test.length() > max){ ans = s.substring(i, j); max = Math.max(max, ans.length()); } } } return ans; } public boolean isPalindrome(String s){ int len = s.length(); for(int i = 0; i < len/2; i++){ if(s.charAt(i) != s.charAt(len - 1 - i)){ return false; } } return true; } }
|