need to understand difference between substrings and subsequences
abbab => subsequences = [aa, bbb, abba, abbab, ...][aa, bbb] is palindromic subsequences
we can remove aa or bbb first then remove the other => done
class Solution {
public int removePalindromeSub(String s) {
if(s == null || s.length() == 0){
return 0;
}
String x = new StringBuilder(s).reverse().toString();
if(x.equals(s))
return 1;
return 2;
}
}
var removePalindromeSub = function(s) {
if (s.length == 0) return 0;
return [...s].reverse().join('') == s ? 1 : 2;
};
Time: O(N), reverse string
Space: O(N)
class Solution:
def removePalindromeSub(self, s: str) -> int:
s_len = len(s)
if s_len == 0:
return 0
i = 0;
j = s_len - 1
while i < s_len / 2:
if s[i] != s[j]:
return 2
i += 1
j -= 1
return 1;
# python... short
def removePalindromeSub(self, s: str) -> int:
if not s:
return 0
if s == s[::-1]:
return 1
return 2
Time: O(N)
Space: O(1)