반응형

https://leetcode.com/problems/removing-stars-from-a-string/description/

 

Removing Stars From a String - LeetCode

Can you solve this real interview question? Removing Stars From a String - You are given a string s, which contains stars *. In one operation, you can: * Choose a star in s. * Remove the closest non-star character to its left, as well as remove the star it

leetcode.com


문제

You are given a string s, which contains stars *.

In one operation, you can:

  • Choose a star in s.
  • Remove the closest non-star character to its left, as well as remove the star itself.

Return the string after all stars have been removed.

Note:

  • The input will be generated such that the operation is always possible.
  • It can be shown that the resulting string will always be unique.

 

Example 1:

Input: s = "leet**cod*e"
Output: "lecoe"
Explanation: Performing the removals from left to right:
- The closest character to the 1st star is 't' in "leet**cod*e". s becomes "lee*cod*e".
- The closest character to the 2nd star is 'e' in "lee*cod*e". s becomes "lecod*e".
- The closest character to the 3rd star is 'd' in "lecod*e". s becomes "lecoe".
There are no more stars, so we return "lecoe".

Example 2:

Input: s = "erase*****"
Output: ""
Explanation: The entire string is removed, so we return an empty string.

Constraints:

  • 1 <= s.length <= 105
  • s consists of lowercase English letters and stars *.
  • The operation above can be performed on s.

풀이

풀이 과정

알파벳 소문자와 '*'로 이루어진 문자열 s가 주어질 때 다음 과정을 거쳐서 만들어지는 문자열을 구하는 문제이다.

  • 문자열 내의 '*' 하나를 선택한다.
  • 선택한 '*'의 왼쪽에 있는 알파벳 중 가장 가까운 알파벳 하나와 선택한 '*'을 제거한다.

 

문자열의 글자들을 처음부터 탐색하면서 스택에 저장해두고 '*'이 나올 때 스택의 가장 위에 있는 문자가 선택한 '*'의 가장 왼쪽에 있는 문자이므로 스택에서 제거해 나가는 식으로 풀이한다.

Stack<Character> stack = new Stack<>();

// 문자열의 모든 글자 탐색
for(int i = 0; i < s.length(); i++){
    // 현재 탐색중인 글자
    char c = s.charAt(i);

    // 현재 탐색중인 글자가 '*'인 경우 스택의 가장 마지막 글자를 제거
    if(c == '*') stack.pop();
    // 현재 탐색중인 글자가 알파벳인 경우 스택에 추가
    else stack.push(c);
}

 

모든 제거 과정이 끝나고 남은 문자열을 return하면 되는데 stack에서 꺼내는 순서는 문자열의 역순이 되므로 앞쪽에서부터 문자를 삽입하여 정답 문자열을 만들어 return해준다.

// 정답 문자열을 만들기 위한 stringBuilder
StringBuilder sb = new StringBuilder();

// 스택에 남아있는 모든 글자 탐색
while(stack.size() > 0){
    // 스택에서 꺼낸 문자열을 앞쪽에 삽입
    sb.insert(0, stack.pop());
}

return sb.toString();

최종 코드

class Solution {
    public String removeStars(String s) {
        Stack<Character> stack = new Stack<>();

        // 문자열의 모든 글자 탐색
        for(int i = 0; i < s.length(); i++){
            // 현재 탐색중인 글자
            char c = s.charAt(i);

            // 현재 탐색중인 글자가 '*'인 경우 스택의 가장 마지막 글자를 제거
            if(c == '*') stack.pop();
            // 현재 탐색중인 글자가 알파벳인 경우 스택에 추가
            else stack.push(c);
        }

        // 정답 문자열을 만들기 위한 stringBuilder
        StringBuilder sb = new StringBuilder();

        // 스택에 남아있는 모든 글자 탐색
        while(stack.size() > 0){
            // 스택에서 꺼낸 문자열을 앞쪽에 삽입
            sb.insert(0, stack.pop());
        }

        return sb.toString();
    }
}

 

반응형
HYOJUN