Make The String Great

ㅋㅋ·2022년 11월 8일
0

알고리즘-leetcode

목록 보기
46/135

대문자 소문자가 섞인 문자열 하나를 받고

이 문자열을 문제에서 말하는 좋은 문자열로 바꾸는 문제이다.

좋은 문자열의 조건은 아래와 같다

A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where:

0 <= i <= s.length - 2
s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa.
class Solution {
public:
    string makeGood(string s) {
        
        const int difference = 'a' - 'A';

        string result = "";

        for (int i = 0; i < s.size(); i++)
        {
            if (result.empty())
            {
                result.push_back(s[i]);
                continue;
            }
            
            if (abs(result.back() - s[i]) == difference)
            {
                result.pop_back();
            }
            else
            {
                result.push_back(s[i]);
            }
        }

        return result;
    }
};

0개의 댓글