题目地址:
https://www.lintcode.com/problem/sub-palindrome/description
给定一个字符串 s s s,求其有多少个不同的回文子串。
直接枚举中心,然后枚举所有以当前位置为中心的回文串,加入一个哈希表中,最后返回哈希表的size即可。代码如下:
import java.util.HashSet;
import java.util.Set;
public class Solution {
/**
* @param s: the string
* @return: the number of substring
*/
public int countSubstrings(String s) {
// Write your code here.
Set<String> set = new HashSet<>();
// 枚举左端点
for (int i = 0; i < s.length(); i++) {
int l = i;
// 枚举右端点
for (int j = 0; j < 2; j++) {
int r = l + j;
while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
set.add(s.substring(l, r + 1));
l--;
r++;
}
// 最后要把左端点恢复原状
l = i;
}
}
return set.size();
}
}
时间复杂度 O ( l s 2 ) O(l_s^2) O(ls2),空间 O ( l s 3 ) O(l_s^3) O(ls3)。