23.04.14 Today’s Leetcode
516. Longest Palindromic Subsequence (medium)
DP Approach
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
n = len(s)
dp = [0] * n
for i in range(n-1, -1, -1):
newdp = [0] * n
newdp[i] = 1
for j in range(i+1, n):
if s[i] == s[j]:
newdp[j] = 2 + dp[j-1]
else:
newdp[j] = max(dp[j], newdp[j-1])
dp = newdp
return dp[-1]
647. Palindromic Substrings (medium)
class Solution {
public int countSubstrings(String s) {
int count=0;
for(int i=0;i<s.length();i++){
count+=extractPalindrome(s,i,i);//odd length
count+=extractPalindrome(s,i,i+1);//even length
}
return count;
}
public int extractPalindrome(String s, int left, int right){
int count=0;
while(left >= 0 && right < s.length() && (s.charAt(left) == s.charAt(right))){
left--;
right++;
count++;
}
return count;
}
}