标签:rar tostring bool else 长度 -- 最大 int amp
public int longestPalindrome(String s) { //预处理 char[] chars = s.toCharArray(); StringJoiner joiner = new StringJoiner("#"); joiner.add(""); for (char c : chars) { joiner.add(String.valueOf(c)); } joiner.add(""); String exString = joiner.toString(); int size = exString.length(); int[] RL = new int[size]; int MaxRight = 0, pos = 0, MaxLen = 0; for (int i = 0; i < size; i++) { if (i < MaxRight) { RL[i] = Math.min(RL[2 * pos - i], MaxRight - i); } else { RL[i] = 1; } //尝试扩展 while (i - RL[i] >= 0 && i + RL[i] < size && exString.charAt(i - RL[i]) == exString.charAt(i + RL[i])) { RL[i]++; } //更新MaxRight,pos if (RL[i] + i - 1 > MaxRight) { MaxRight = RL[i] + i - 1; pos = i; } //更新最大长度 MaxLen = Math.max(MaxLen, RL[i]); } return MaxLen - 1; }
public int dpLongestPalindrome(String s) { int n = s.length(); boolean[][] pal = new boolean[n][n]; //pal[i][j] 表示s[i...j]是否是回文串 int maxLen = 0; for (int i = 0; i < n; i++) { // i作为终点 int j = i; //j作为起点 while (j >= 0) { if (s.charAt(j) == s.charAt(i) && (i - j < 2 || pal[j + 1][i - 1])) { pal[j][i] = true; maxLen = Math.max(maxLen, i - j + 1); } j--; } } return maxLen; }
标签:rar tostring bool else 长度 -- 最大 int amp
原文地址:http://www.cnblogs.com/skyke/p/7399357.html