【Lintcode】1856. Sub-palindrome
題目地址:
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)。
相關文章
- [LintCode] Daily TemperaturesAI
- LintCode 子樹
- LintCode-Backpack
- LintCode-HeapifyAPI
- [LintCode] Permutation in String
- LintCode 主元素 II
- LintCode 解碼方法
- LintCode-Search for a Range
- LintCode-K Sum
- LintCode-Word SegmentationSegmentation
- LintCode-Hash FunctionFunction
- LintCode-Fast PowerAST
- Lintcode-Max Tree
- LintCode-Partition Array
- LintCode-Subarray Sum
- LintCode-Majority Number
- LintCode-A+B Problem
- LintCode-BackPack II
- LintCode-Previous Permuation
- LintCode 字串比較字串
- [LintCode] 3Sum Smaller
- 【Lintcode】572. Music PairsAI
- 【Lintcode】576. Split Array
- 【Lintcode】1736. Throw Garbage
- LintCode - A + B 問題(普通)
- Lintcode 反轉整數
- 表示式展開-LintCode
- LintCode 最大正方形
- LintCode 奇偶分割陣列陣列
- LintCode 搜尋插入位置
- LintCode 刪除數字
- LintCode-Maximum Subarray II
- LintCode-Maximum Subarray III
- LintCode-Rotate String
- LintCode-Word Search II
- LintCode-Rehashing
- LintCode-Subarray Sum Closest
- LintCode-Maximum Subarray Difference