상세 컨텐츠

본문 제목

2390. Removing Stars From a String

LeetCode

by 10002s 2023. 11. 16. 00:04

본문

Removing Stars From a String - LeetCode

문자열 s가 주어지며, 이 문자열에는 별표(*)가 포함되어 있습니다.
한 번의 연산에서 다음을 수행할 수 있습니다:
s에서 별표를 선택합니다.
해당 별표의 가장 가까운 왼쪽에 있는 비 별표 문자를 제거하고, 별표 자체도 제거합니다.
모든 별표가 제거된 후의 문자열을 반환하세요.

 

 

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.

 

풀이과정 설명:

문자열을 순회하면서 별표를 찾습니다.
각 별표마다 가장 가까운 왼쪽에 있는 비 별표 문자를 제거합니다.
위의 과정을 반복하여 모든 별표를 제거하고 최종 문자열을 반환합니다.

 

 

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

        for(String _s: s.split("")){
            if(_s.equals("*")){
                stk.pop();
            }else{
                stk.add(_s);
            }
        }

        String retStr = "";
        for(String _s: stk){
            retStr += _s;
        }
        return retStr;
    }
}

 

반응형

'LeetCode' 카테고리의 다른 글

933. Number of Recent Calls  (0) 2023.11.17
735. Asteroid Collision  (0) 2023.11.16
1657. Determine if Two Strings Are Close  (0) 2023.11.13
724. Find Pivot Index  (0) 2023.11.11
1732. Find the Highest Altitude  (0) 2023.11.11

관련글 더보기