✏️ 문제 설명
숫자와 "Z"가 공백으로 구분되어 담긴 문자열이 주어집니다. 문자열에 있는 숫자를 차례대로 더하려고 합니다. 이 때 "Z"가 나오면 바로 전에 더했던 숫자를 뺀다는 뜻입니다. 숫자와 "Z"로 이루어진 문자열 s가 주어질 때, 머쓱이가 구한 값을 return 하도록 solution 함수를 완성해보세요.
✏️ code 1차
public int solution(String s) {
String arr[] = s.split(" ");
int result = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i].equals("Z")) {
result -= Integer.parseInt(arr[i-1]);
} else {
result += Integer.parseInt(arr[i]);
}
}
return result;
}
✏️ code 2차
📌 Stack의 FILO 특성을 고려하여 Z가 나올 때마다 pop하는 것으로 풀어보았습니다.
public int solution2(String s) {
String arr[] = s.split(" ");
Stack<Integer> stack = new Stack<>();
for (String str : arr) {
if (str.equals("Z")) {
stack.pop();
} else {
stack.push(Integer.parseInt(str));
}
}
int result = 0;
for (int n: stack) {
result += n;
}
return result;
}
반응형