[M] 394. Decode String

YJ·2025년 4월 26일

leetcode

목록 보기
34/100

https://leetcode.com/problems/decode-string

문제

input이 3[a]2[bc] 면, output으로 aaabcbc 출력
input이 3[a2[c]] 면, output으로 accaccacc 출력

답안

public String decodeString(String s) {
	Stack<Character> st = new Stack<>();
	for (char c : s.toCharArray()) {
		if (c != ']') {
			st.push(c);
			continue;
		}
		String part = "";
		while (st.peek() != '[') {
			part = st.pop() + part;
		}
		st.pop(); 
		int repeat = 0;
		int digit = 1;
		while (!st.isEmpty() && Character.isDigit(st.peek())) {
			repeat += (st.pop() - '0') * digit;
			digit *= 10;
		}
		for (int i = 0; i < repeat; i++) {
			for (char tmp : part.toCharArray()) {
				st.push(tmp);
			}
		}
	}
	return st.stream()
		.map(x -> x.toString())
		.collect(Collectors.joining(""));
}

백터로.. ] 이면 [ 나올 때까지 pop

메모

  • char 가 digit 인지 확인 => Character.isDigit(char)
  • String 을 integer 로 변환 => Integer.valueOf(str)
  • Character 를 Integer 로 변환 => char - '0'
profile
Hello

0개의 댓글