给定一个字符串,返回这个字符串中有多少个回文子串。
两个相同的回文子串出现在不同的位置,认为是2个回文子串。
a、aa、aaa、aba、aabaa、abcba均认为是回文子串。
中心扩展算法
import java.util.*; public class Solution { /** * * @param str string字符串 * @return int整型 */ public int palindromeCount (String str) { int ans = 0; for (int center = 0; center < str.length(); center++) { ans += expand(str, center, center) + expand(str, center, center + 1); } return ans; } private int expand(String str, int left, int right) { int ans = 0; while (left >= 0 && right < str.length() && str.charAt(left) == str.charAt(right)) { ans++; left--; right++; } return ans; } }
import java.util.*; public class Solution { /** * * @param str string字符串 * @return int整型 */ public int palindromeCount (String str) { char[] cs = str.toCharArray(); int res = 0; int n = str.length(); boolean[][] f = new boolean[n][n]; for (int j = 0; j < n; j++) { for (int i = 0; i <= j; i++) { if (i == j) { f[i][j] = true; } else if (i + 1 == j) { f[i][j] = cs[i] == cs[j]; } else { f[i][j] = f[i + 1][j - 1] && cs[i] == cs[j]; } if (f[i][j]) { res++; } } } return res; } }
public static int getHuiWenNumber(String str){ int number=0; for(int i=0;i<str.length();i++){ for(int left=i,right =i;left>=0 &&right<str.length();left--,right++){ if(str.charAt(left)!=str.charAt(right)){ break; } number++; } } return number; }
import java.util.*; public class Solution { /** * * @param str string字符串 * @return int整型 */ public int palindromeCount (String str) { char[] charArr = manacherString(str); int[] pArr = new int[charArr.length]; int index = 0; //回文串中心位置 int pR = -1; //回文串右边界 for (int i = 0; i < charArr.length; ++i) { pArr[i] = i < pR ? Math.min(pArr[2 * index - i], pR - i) : 1; while (i - pArr[i] >= 0 && i + pArr[i] < charArr.length) { if (charArr[i - pArr[i]] == charArr[i + pArr[i]]) { pArr[i]++; } else { break; } } if (i + pArr[i] > pR) { pR = i + pArr[i]; index = i; } } int ans =0; for(int i=0;i<pArr.length;++i){ ans += pArr[i]/2; } return ans; } private static char[] manacherString(String str) { char[] charArr = str.toCharArray(); char[] res = new char[charArr.length * 2 + 1]; int index = 0; for (int i = 0; i < res.length; ++i) { res[i] = (i & 1) == 0 ? '#' : charArr[index++]; } return res; } }
public static Integer palindromeNum(String str) { int num = 0; if (StringUtils.isNotBlank(str)) { int index = 0; int nextIndex; while (index < str.length()) { nextIndex = str.indexOf(str.charAt(index), index + 1); if (nextIndex == -1 || !isPalindrome(str.substring(index, nextIndex + 1))) { index++; continue; } else { num++; } index = nextIndex; } } return num; } public static Boolean isPalindrome(String str) { if (StringUtils.isNotBlank(str) && str.length() > 1) { char[] chars = str.toCharArray(); for (int i = 0; i < str.length() / 2; i++) { if (chars[i] != chars[str.length() - i - 1]) { return false; } } return true; } return false; }