2021年9月6日 星期一

[LeetCode] 647. Palindromic Substrings

 轉自LeetCode

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.

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

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
}
}

沒有留言:

張貼留言