647. 回文子串
程序员文章站
2022-03-24 14:33:30
...
题目:
题解:
1. 题解一:中心扩展算法
- 解释一:
- 解释二:
- 解释三:
2. 题解二:动态规划
- 解释一:
- 解释二:
代码:
1. 代码一:中心扩展算法
public class code647 {
// 解法1: 中心扩展算法
public int num = 0;
public int countSubstrings(String s)
{
for(int i = 0; i < s.length(); i++)
{
count(s, i, i); //回文串长度为奇数
count(s, i, i + 1); //回文串长度为偶数
}
return num;
}
public void count(String s, int start, int end)
{
while(start >= 0 && end < s.length() && s.charAt(start) == s.charAt(end))
{
num++;
start--;
end++;
}
}
public static void main(String[] args) {
code647 test1 = new code647();
String s1 = "abc";
int res1 = test1.countSubstrings(s1);
System.out.println(res1);
code647 test2 = new code647();
String s2 = "aaa";
int res2 = test2.countSubstrings(s2);
System.out.println(res2);
}
}
2. 代码二:动态规划
public class code647 {
// 解法2: 动态规划
public int countSubstrings(String s)
{
int len = s.length();
// dp[i][j] 表示字符串 s 在 [i, j] 区间的子串是否是一个回文串。
boolean dp[][] = new boolean[len][len];
int count = 0;
for(int j = 0; j < len; j++)
{
for(int i = 0; i <= j; i++)
{
// 当 (s.charAt(i) == s.charAt(j) 时,当元素个数为 1, 2, 3 ... n 个时,一定为回文子串
if(s.charAt(i) == s.charAt(j) && (j - i < 2 || dp[i + 1][j - 1]))
{
dp[i][j] = true;
count++;
}
}
}
return count;
}
public static void main(String[] args) {
code647 test1 = new code647();
String s1 = "abc";
int res1 = test1.countSubstrings(s1);
System.out.println(res1);
code647 test2 = new code647();
String s2 = "aaa";
int res2 = test2.countSubstrings(s2);
System.out.println(res2);
}
}