給定一個字符串,你的任務是計算這個字符串中有多少個回文子串。
具有不同開始位置或結束位置的子串,即使是由相同的字符組成,也會被計為是不同的子串。
示例 1:
輸入: "abc"
輸出: 3
解釋: 三個回文子串: "a", "b", "c".
示例 2:
輸入: "aaa"
輸出: 6
說明: 6個回文子串: "a", "a", "a", "aa", "aa", "aaa".
注意:
輸入的字符串長度不會超過1000。
思路:我一開始就想枚舉每個中心往兩邊擴唄,后來像動態規劃一樣是o(n*n)的,看答案也沒有更好的方法。
注意:奇回文偶回文的問題
class Solution {public int countSubstrings(String s) {int count = 0;for(int i = 0; i < s.length(); i++){count += countPalindrome(s, i, i);count += countPalindrome(s, i, i + 1);}return count;}public int countPalindrome (String s, int left, int right){int count = 0;while(left >= 0 && right < s.length() && s.charAt(left--) == s.charAt(right++))count++;return count;}
}
?