📖 오늘의 학습 키워드
스택
[Mini Parser]
https://leetcode.com/problems/mini-parser/description/
class Solution {
public NestedInteger deserialize(String s) {
if(s.charAt(0) != '[') {
return new NestedInteger(Integer.parseInt(s));
}
StringBuilder num = new StringBuilder();
Deque<NestedInteger> stack = new ArrayDeque<>();
for(char c : s.toCharArray()) {
if(c == '[') {
stack.push(new NestedInteger());
}
else if(c == ',' || c == ']'){
if(num.length() > 0) {
stack.peek().add(new NestedInteger(Integer.parseInt(num.toString())));
num.setLength(0);
}
if(stack.size() > 1 && c == ']') {
NestedInteger nestedInteger = stack.pop();
stack.peek().add(nestedInteger);
}
}
else {
num.append(c);
}
}
return stack.peek();
}
}
s가 '['(대괄호)로 시작하지 않으면, s는 한 개의 정수로 이루어져 있다. 해당 정수로 초기화한 NestedInteger를 생성하고 정답으로 반환한다.s에 포함된 정수들을 저장할 StringBuilder num을 선언한다.[을 만날 때마다 nested list를 생성하고 이를 저장할 stack을 Deque로 선언한다.s를 for 문으로 돌며 각 문자 c에 대해 다음 과정을 수행한다.c가 '['라면, 빈 NestedInteger를 생성하고 stack에 삽입한다.c가 ','나 ']'라면, stack 최상단의 NestedInteger에 정수 num으로 초기화한 NestedInteger를 추가한다. 그리고 num 내 모든 문자열을 제거한다.stack의 크기가 1보다 크고 c가 ']'라면, stack 최상단의 NestedInteger를 꺼내서 이를 다시 현재 stack 최상단의 NestedInteger에 추가한다.c가 위 모든 경우에 해당하지 않는다면, c가 숫자라는 의미이고 이를 num에 추가한다.stack 최상단의 NestedInteger를 정답으로 반환한다.