Given a string s
, return the number of palindromic substrings in it.
A string is a palindrome when it reads the same backward as forward.
A substring is a contiguous sequence of characters within the string.
Example 1:
Input: s = "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: s = "aaa" Output: 6 Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
Constraints:
1 <= s.length <= 1000
s
consists of lowercase English letters.
class Solution { public int countSubstrings(String s) { int n = s.length(); int res = n; for(int i = 2; i <= n; i++) { for(int j = 0; j <= n - i; j++) { if(help(s.substring(j, j + i))) { res++; } } } return res; } public boolean help(String s) { int l = 0, r = s.length() - 1; while(l < r) { if(s.charAt(l) != s.charAt(r)) return false; l++; r--; } return true; } }
mlgb, brute force管上。
class Solution { int res = 0; public int countSubstrings(String s) { int n = s.length(); for(int i = 0; i < s.length(); i++) { help(s, i, i); help(s, i, i + 1); } return res; } public void help(String s, int l, int r) { while(l >= 0 && r <= s.length() - 1 && s.charAt(l) == s.charAt(r)) { res++; l--; r++; } } }
或者用一种和5一样的midexpansion方法,每次check这一位开始的odd和even的substring看是不是palindrome。