넘치게 채우기

[LeetCode] 1544. Make The String Great 본문

PS/LeetCode

[LeetCode] 1544. Make The String Great

riveroverflow 2024. 4. 5. 12:08
728x90
반응형

https://leetcode.com/problems/make-the-string-great/description/

Leetcode - Make The String Great

문제 유형 : 문자열 처리

문제 난이도 : Easy

 

문제

Given a string s of lower and upper case English letters.

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.

To make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good.

Return the string after making it good. The answer is guaranteed to be unique under the given constraints.

Notice that an empty string is also good.

 

문자열 s가 주어진다. 영문 소문자와 대문자로 이루어져있다.

좋은 문자열은 두 인접한 문자끼리 서로 대문서-소문자 관계가 아닌 문자열을 말한다.

s문자열을 좋은 문자열로 만들고 난 결과를 반환하시오. 한 가지 정답만 나오도록 케이스가 주어집니다.

 

풀이

임시 문자열 temp를 생성한다. 

문자열 s를 순차적으로 읽으면서 temp에 담는다. 나쁜 관계의 인접한 문자들을 보면, 임시 문자열에 담지 않는다.

s에 temp를 담는다.

만약 나쁜 관계가 검출되지 않으면, 멈추고 반환한다.

 

코드

C++

class Solution {
public:
    string makeGood(string s) {
        while(true) {
            string temp = "";
            bool flag = false;
            for(int i = 0; i < s.size(); i++) {
                if(i == s.size()-1) {
                    temp += s[i];
                    continue;
                }
                
                if((s[i] + 32 == s[i+1]) || (s[i+1] + 32 == s[i])) {
                    flag = true;
                    i++;
                    continue;
                }
                temp += s[i];
            }
            s = temp;

            if(!flag) break;
        }

        return s;
    }
};
 
728x90
반응형