【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] Permutation in String
- [LintCode/LeetCode] Meeting RoomsLeetCodeOOM
- Lintcode 1263. Is Subsequence
- 【Lintcode】1189. Minesweeper
- [LeetCode/LintCode] Largest Palindrome ProductLeetCode
- [LintCode/LeetCode] Contains Duplicate IIILeetCodeAI
- [LintCode] Check Full Binary Tree
- [LintCode/LeetCode] Remove Duplicate LettersLeetCodeREM
- [LintCode] 3Sum Smaller
- 【Lintcode】1615. The Result of Investment
- [LintCode] Binary Tree Level Order
- 【Lintcode】1736. Throw Garbage
- 【Lintcode】1665. Calculate Number
- 【Lintcode】1789. Distinguish UsernameNGUI
- 【Lintcode】1562. Number of RestaurantsREST
- 【Lintcode】576. Split Array
- 【Lintcode】1267. Lexicographical Numbers
- 【Lintcode】141. Sqrt(x)
- 【Lintcode】1415. Residual Product
- 【Lintcode】1230. Assign CookiesCookie
- 【Lintcode】1732. Snakes and Ladders
- 【Lintcode】1218. Number Complement
- 【Lintcode】1850. Pick ApplesAPP
- 【Lintcode】572. Music PairsAI
- 【Lintcode】318. Character Grid
- 【Lintcode】1891. Travel Plan
- [LintCode/LeetCode] Check Sum of K PrimesLeetCode
- [LintCode]NumberofIslands(島嶼個數)
- lintcode-514-柵欄染色
- 【Lintcode】1322. Product Equal B
- 【Lintcode】191. Maximum Product Subarray
- 【Lintcode】1786. Pub Sub Pattern
- 【Lintcode】1793. Balanced Sales Array
- 【Lintcode】1623. Minimal Distance In The Array
- 【Lintcode】1484. The Most Frequent Word
- 【Lintcode】1025. Custom Sort String
- 【Lintcode】1485. Holy Grail spellAI