1. 생각
- 전형적인 스택 문제
- ")"까지 보고 반복문
2. 코드
import java.util.*;
class Solution {
public String solution(String s){
String answer = "";
Stack<String> st = new Stack<>();
for (char c : s.toCharArray()) {
if(c == ')') {
String tmp = "";
while (!st.empty()) {
String t = st.pop();
if(t.equals("(")) {
String num = "";
while (!st.empty() && Character.isDigit(st.peek().charAt(0))) {
num = st.pop() + num;
}
String res = "";
int cnt = 0;
if(num.equals("")) cnt = 1;
else cnt = Integer.parseInt(num);
for (int i = 0; i < cnt; i++) {
res += tmp;
}
st.push(res);
break;
} else {
tmp = t + tmp;
}
}
} else {
st.push(String.valueOf(c));
}
}
for(String x : st) {
answer += x;
}
return answer;
}
public static void main(String[] args){
Solution T = new Solution();
System.out.println(T.solution("3(a2(b))ef"));
System.out.println(T.solution("2(ab)k3(bc)"));
System.out.println(T.solution("2(ab3((cd)))"));
System.out.println(T.solution("2(2(ab)3(2(ac)))"));
System.out.println(T.solution("3(ab2(sg))"));
}
}
[결과]
abbabbabbef
ababkbcbcbc
abcdcdcdabcdcdcd
ababacacacacacacababacacacacacac
absgsgabsgsgabsgsg