[LeetCode] Make The String Great

준규·2023년 1월 11일
0

1.문제


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 문자열에서 삭제를 해준다.

이 과정을 더이상 삭제를 할 수 없을 정도까지 진행한 결과를 리턴하면 된다.


Example 1

Input: s = "leEeetcode"
Output: "leetcode"
Explanation: In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode".

Example 2

Input: s = "abBAcC"
Output: ""
Explanation: We have many possible scenarios, and all lead to the same answer. For example:
"abBAcC" --> "aAcC" --> "cC" --> ""
"abBAcC" --> "abBA" --> "aA" --> ""

Example 3

Input: s = "s"
Output: "s"

Constraints:

  • 1 <= s.length <= 100
  • s contains only lower and upper case English letters.

2.풀이

  1. stack을 활용하여 stack의 top 요소와 현재 철자의 대소문자를 체크한다.
  2. 만약 전혀 다른 문자이거나 대소문자가 다른 경우가 아니라면 stack에 넣어준다.

/**
 * @param {string} s
 * @return {string}
 */
const makeGood = function (s) {
  const stack = [];

  for (let i = 0; i < s.length; i++) {
    if (
      stack.length &&
      Math.abs(s[i].charCodeAt() - stack[stack.length - 1].charCodeAt()) === 32
    ) {
      // stack 이 비어있지 않고 현재 알파벳과 stack의 top의 알파벳이 대소문자만 다른 같은 철자일 때 stack 최상단 값을 뺀다.
      stack.pop();
    } else {
      // stack이 비어있거나 전혀 다른 두 알파벳이라면 스택에 현재 알파벳을 넣어준다.
      stack.push(s[i]);
    }
  }

  return stack.join("");
};

3.결과

profile
안녕하세요 :)

0개의 댓글