import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String s = sc.next();
double arr[] = new double[n];
for(int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
Stack<Double> stack = new Stack<>();
for(char c : s.toCharArray()) {
if(Character.isAlphabetic(c)) {
stack.push(arr[c - 'A']);
} else {
double a = stack.pop();
double b = stack.pop();
if(c == '+') {
stack.push(a + b);
} else if(c == '-') {
stack.push(b - a);
} else if(c == '*') {
stack.push(a * b);
} else if(c == '/') {
stack.push(b / a);
}
}
}
System.out.printf("%.2f\n", stack.pop());
}
}
스택을 이용해서 문자가 알파벳인 경우는 스택에 피연산자로써 넣고, 연산자인 경우에는 스택에 있는 피연산자 두개를 pop해서 뽑고 계산해서 다시 스택에 push하는 방식으로 구현하였다.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
Stack<Character> stack = new Stack<>();
StringBuilder sb = new StringBuilder();
for(char c : s.toCharArray()) {
if(Character.isAlphabetic(c)) {
sb.append(c);
} else if(c == '(') {
stack.push(c);
} else if(c == ')') {
while(!stack.isEmpty()) {
if(stack.peek() == '(') {
stack.pop();
break;
}
sb.append(stack.pop());
}
} else { // 연산자일 경우
while(!stack.isEmpty() && priority(stack.peek()) >= priority(c)) {
sb.append(stack.pop());
}
stack.push(c);
}
}
while(!stack.isEmpty()) {
sb.append(stack.pop());
}
System.out.println(sb);
}
static int priority(char c) {
if(c == '(') {
return 0;
}
if(c == '+' || c == '-') {
return 1;
}
return 2;
}
}
스택과 우선순위를 매겨주는 함수인 priority를 이용해서 해결하였다.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
int arr[] = new int[26];
for(char c : s.toCharArray()) {
arr[c - 'a']++;
}
for(int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
알파벳 개수를 셀 arr 배열을 생성하고 문자열을 for문을 돌려서 문자에 해당하는 arr 요소를 1씩 증가시켜준다. 그리고 나서 arr 배열을 출력해주면 된다.