Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
Example 1:
Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
Note:
The input string length won't exceed 1000.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindromic-substrings
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
1. 暴力破解
对于每一个数字,以它为中心,向两边开始遍历,如果是循环串就统计加一。因为要区别奇数和偶数的情况,所以还有一种,以两个数字为中心,向两边遍历。
class Solution {
private int ans = 0;
public int countSubstrings(String s) {
for (int i = 0; i < s.length(); i++) {
search(i, i, s);
search(i, i + 1, s);
}
return ans;
}
private void search(int i, int j, String s) {
while (i >= 0 && j < s.length()) {
if (s.charAt(i) == s.charAt(j)) {
ans++;
i--;
j++;
} else {
return;
}
}
}
}
2. 动态规划
用Boolean dp[i][j]表示字符串的i到j位是否是回文子串,那么
如果s.charAt(i) == s.charAt(j),那么dp[j][i] = dp[j + 1][i - 1],如果dp[j][i]是true,那么就最终结果加一。
class Solution {
private int ans = 0;
public int countSubstrings(String s) {
boolean [][] dp = new boolean[s.length()][s.length()];
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j <= i; j++) {
if (i == j) {
dp[j][i] = true;
ans++;
} else {
if (j + 1 == i) {
if (s.charAt(i) == s.charAt(j)) {
dp[j][i] = true;
ans++;
}
} else {
if (s.charAt(i) == s.charAt(j)) {
dp[j][i] = dp[j + 1][i - 1];
if (dp[j][i]) {
ans++;
}
}
}
}
}
}
return ans;
}
}
本文介绍了一种算法,用于统计给定字符串中回文子串的数量,通过两种方法实现:暴力破解和动态规划。暴力破解法以每个字符为中心向两边扩展;动态规划则使用布尔型二维数组记录子串是否为回文。
510

被折叠的 条评论
为什么被折叠?



