[leetcode] Remove Palindromic Subsequences

임택·2021년 3월 9일
0

알고리즘

목록 보기
51/63

problem

code

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

1st try:reverse

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)

2nd try: check if it is a palindrome


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)

profile
캬-!

0개의 댓글