본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 1332. Remove Palindromic Subsequences

반응형

https://leetcode.com/problems/remove-palindromic-subsequences/description/

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

간단 구현문제였습니다.

📕 풀이방법

📔 풀이과정

모든 문자열은 a또는 b로만 이루어져 있고 부분 문자열은 순서 상관 없이 고를 수 있으므로 최악의 횟수는 a, b각각 모아 지우는 경우인 2가 됩니다. 

 

📔 정답 출력 | 반환

1. s가 "" (빈 문자열)인 경우 : 지울 문자가 없으므로 0을 반환합니다.

2. s가 palindrome인 경우 : 해당 문자열을 1번만 지우면 빈 문자열이 되므로 1을 반환합니다.

3. 이외 : a, b 모아서 각각 1회씩 지우면 되므로 2를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    bool isPalindrome(string s) {
        for(int i = 0; i < s.size() / 2; i++) {
            if(s[i] != s[s.size()-1-i]) return false;
        }
        return true;
    }

    int removePalindromeSub(string s) {
        if(s.empty()) return 0;
        if(isPalindrome(s)) return 1;
        return 2;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.