Solution 1) 내 풀이
class Solution {
    public int solution(String s) {
        int answer = 0;
        String[] tmp = s.split(" ");

        for (int i = 0; i < tmp.length; i++) {
            if (tmp[i].equals("Z")) {
                answer -= Integer.parseInt(tmp[i - 1]);
            } else {
                answer += Integer.parseInt(tmp[i]);
            }
        }
        return answer;
    }
}
Solution 2) 다른 사람의 풀이_stack 활용
import java.util.*;

class Solution {
    public int solution(String s) {
        int answer = 0;
        Stack<Integer> stack = new Stack<>();

        for (String w : s.split(" ")) {
            if (w.equals("Z")) {
                stack.pop();
            } else {
                stack.push(Integer.parseInt(w));
            }
        }
        for (int i : stack) {
            answer += i;
        }
        return answer;
    }
}
아마 문제의 의도는 stack을 활용하게 했던 게 아닌가 싶다.
stack에 최적화 돼있던 문제인 것 같다. (직전의 요소를 빼야하는 조건이 있기에)
편한 방법만 고수하지 말고 다방면으로 생각하고 활용할 수 있어야겠다.

 

+ Recent posts