📌 BaseBall Game - 문제
- +면 두 숫자 더해서 넣기, D면 전 숫자 double, C면 지우기
https://leetcode.com/problems/baseball-game/
📌 풀이
🔥 주의점
- 문제를 잘 봐야 한다.
문제 잘못봐서, 당연히 계산하면 스택에서 빼는걸로 생각했다 ( 계산기처럼 )
- stack 은 뺀 거 그대로 넣을라면, 뺀 순서의 반대로 넣어주어야 원래 순서가 유지된다.
📌 코드
public class Main {
public static void main(String[] args) {
Solution solution = new Solution();
int i = solution.calPoints(new String[]{"5", "-2", "4", "C", "D", "9", "+", "+"});
System.out.println(i);
}
static class Solution {
public int calPoints(String[] ops) {
Stack<String> stack = new Stack<>();
Set<String> set = new HashSet<>();
set.add("C");
set.add("D");
set.add("+");
for(int i=0;i<ops.length;i++){
if(set.contains(ops[i])){
if(ops[i].equals("C")){
stack.pop();
}else if(ops[i].equals("D")){
String pop = stack.pop();
int i1 = Integer.parseInt(pop);
i1 *= 2;
stack.push(pop);
stack.push(String.valueOf(i1));
}else if(ops[i].equals("+")){
String p1 = stack.pop();
String p2 = stack.pop();
int p3 = Integer.parseInt(p1) + Integer.parseInt(p2);
stack.push(p2);
stack.push(p1);
stack.push(String.valueOf(p3));
}
}else{
stack.push(ops[i]);
}
}
int res=0;
for(String s : stack){
res += Integer.parseInt(s);
}
return res;
}
}
}
📌 Valid Parentheses 문제
- 괄호 짝 맞추기 문제
📌 풀이
🔥 주의점
- switch - case 할 때, break 안 걸어주면 그대로 쭉 가서 default 때문에 stack에 넣어진다.
- if else -> else 어케하지? 생각이 들었다. default로 하면 default가 else가 된다.
📌 코드
public class Main {
public static void main(String[] args) {
Solution solution = new Solution();
boolean valid = solution.isValid("()[]{}");
System.out.println(valid);
}
static class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for(int i=0;i<s.length();i++){
char c = s.charAt(i);
switch (c){
case ')' :
if (stack.isEmpty() || stack.peek() != '(') return false;
else{
stack.pop();
}
break;
case ']':
if(stack.isEmpty() ||stack.peek() != '[') return false;
else{
stack.pop();
}
break;
case '}':
if(stack.isEmpty() ||stack.peek() != '{') return false;
else{
stack.pop();
}
break;
default : stack.push(c);
}
}
return stack.isEmpty();
}
}
}
'알고리즘 > 📌leetcode' 카테고리의 다른 글
Maximum Depth of Binary Tree (0) | 2021.11.30 |
---|---|
Binary Tree Level Order Traversal (0) | 2021.11.30 |
Reverse LinkedList (0) | 2021.11.28 |
Merge K Sorted List (0) | 2021.11.28 |
Add Two Numbers (0) | 2021.11.28 |
댓글