TIL
[코테연습] 2390. Removing Stars From a String
크라00
2024. 6. 24. 16:37
- 스택 / 큐 문제
- 특정 글자 ex ) leet**cod*e 가 주어지고, * 에 해당하면 그 전의 글자를 지우는 문제
- 문제 풀이
1. 글자를 split() 함수로 String[] arr 초기화한다.
2. for 문으로 String[] arr 를 탐색하며 Stack 에 담는다.
2-1. * 문자일 경우에는 stack.pop() 으로 글자를 꺼낸다.
2-2. 다른 문자일 경우에는 stack.add() 로 글자를 넣는다.
3. 모두 담은 stack 을 queue 에 담는다.
4. queue 가 isEmpty()될때까지 while 문으로 글자를 꺼내어 StringBuilder 로 조합한다.
5. 해당 글자 리턴
class Solution {
public String removeStars(String s) {
String[] arr = s.split("");
Stack<String> stack = new Stack<>();
for (int i = 0; i < arr.length; i++) {
String t = arr[i];
if ("*".equals(t)) {
stack.pop();
} else {
stack.add(t);
}
}
Queue<String> queue = new LinkedList<>(stack);
StringBuilder sb = new StringBuilder();
while(!queue.isEmpty()) {
sb.append(queue.poll());
}
return sb.toString();
}
}