import java.util.Stack;

public class Solution {
	
	// 압축 문자열 풀기
	
	public static String solution(String compressed) {
		String answer = ""; // 최종 문자열을 담을 변수
		Stack<Character> charStack = new Stack<>(); // 영단어와 '(' 괄호를 담을 스택
		Stack<Integer> numStack = new Stack<>(); // 숫자를 담을 스택
		String tempStr = ""; // 임시 문자열을 담을 변수
		int tempNum = 0; // 임시 숫자를 담을 변수
		String repeatStr = ""; // 반복 문자열을 담을 변수
		StringBuilder sb = new StringBuilder(); // 문자열을 보다 효율적으로 이어주기 위한 StringBuilder
		
		for (int i = 0; i < compressed.length(); i++) { // compressed 한 글자씩 체크
			
			tempNum = 0; // 초기화
			
			if (compressed.charAt(i) >= '0' && compressed.charAt(i) <= '9') { // 1. 숫자라면
				
				while (compressed.charAt(i) >= '0' && compressed.charAt(i) <= '9') {
					tempNum = tempNum * 10 + compressed.charAt(i) - '0'; // 하나의 연속된 숫자라면 이전 숫자의 단위를 * 10하여 올리고 현재 숫자를 일의 자리로 더함
					i++; // 하나의 연속된 숫자라면 i 증가
				}
				
				i--; // while문 빠져나오기 전 마지막 i++가 있었으므로 다시 i--
				numStack.push(tempNum); // 숫자를 넘버 스택에 담기
			} else if (compressed.charAt(i) == '(') { // 2. 여는 괄호라면
				
				if (compressed.charAt(i - 1) >= '0' && compressed.charAt(i - 1) <= '9') { // 여는 괄호 전에 숫자가 있다면
					charStack.push(compressed.charAt(i)); // 여는 괄호 담기
				} else { // 여는 괄호 전에 숫자가 없다면 이것은 1이 생략된 것
					numStack.push(1); // 1을 넘버 스택에 담기
					charStack.push(compressed.charAt(i)); // 여는 괄호 담기
				}
			} else if (compressed.charAt(i) == ')') { // 3. 닫는 괄호라면
				
				tempStr = ""; // 초기화
				tempNum = 0; // 초기화
				sb.setLength(0); // 초기화
				
				if (!numStack.isEmpty()) {
					tempNum = numStack.pop(); // 가장 마지막에 들어온 숫자 꺼내기
				}
				
				while (!charStack.isEmpty() && charStack.peek() != '(') { // 여는 괄호가 아니면
					tempStr = charStack.pop() + tempStr; // 스택에서 꺼내며 임시 문자열 앞에 붙이기 // hi
				}
				
				if (!charStack.isEmpty() && charStack.peek() == '(') { // 여는 괄호면
					charStack.pop(); // 버리기
				}
				
				for (int j = 0; j < tempNum; j++) {
					sb.append(tempStr); // hihihihihihihihihihi
				}
				
				repeatStr = sb.toString();
				
				for (int k = 0; k < repeatStr.length(); k++) { // hihihihihihihihihihi
					charStack.push(repeatStr.charAt(k));
				}
				
				repeatStr = ""; // 초기화
				
			} else { // 4. 영단어라면
				charStack.push(compressed.charAt(i));
			}
		}
		
		while (!charStack.isEmpty()) {
			answer = charStack.pop() + answer;
		}
		
		return answer;
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String compressed = "2(10(hi)co)";
		
		System.out.println(solution(compressed)); // hihihihihihihihihihicohihihihihihihihihihico
	}
}

프로그래머스 압축된 문자열 풀기 문제 풀이 Java

+ Recent posts