Given a string
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.
Solution
可以沿用 longest palindromic substring 的概念
用 dp[i][j] 來表示 s[i] 到 s[j] 是否是一個回文串
如果是,就把 counter + 1
code 如下
Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
fun countSubstrings(s: String): Int { | |
var dp = Array(s.length) { Array(s.length) {false} } | |
var ans = 0 | |
for(j in s.indices) { | |
for (i in 0..j) { | |
dp[i][j] = s[i] == s[j] && (j - i < 2 || dp[i+1][j-1]) | |
if(dp[i][j]) { | |
++ans | |
} | |
} | |
} | |
return ans | |
} | |
} |
沒有留言:
張貼留言