class Solution {
public int calculate(String s) {
int last = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == " ") {
s = s.substring(0, i) + s.substring(i+1);
}
}
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == '/') {
String before = s.substring(0, i - 1);
String after = s.substring(i+2);
int val = Integer.valueOf(s.charAt(i-1)) / Integer.valueOf(s.charAt(i+1));
String v = Integer.toString(val);
s = before + v + after;
}
if (s.charAt(i) == '*') {
String before = s.substring(0, i - 1);
String after = s.substring(i+2);
int val = Integer.valueOf(s.charAt(i-1)) * Integer.valueOf(s.charAt(i+1));
String v = Integer.toString(val);
s = before + v + after;
}
}
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == '+') {
String before = s.substring(0, i - 1);
String after = s.substring(i+2);
int val = Integer.valueOf(s.charAt(i-1)) + Integer.valueOf(s.charAt(i+1));
String v = Integer.toString(val);
s = before + v + after;
}
if (s.charAt(i) == ' ') {
String before = s.substring(0, i - 1);
String after = s.substring(i+2);
int val = Integer.valueOf(s.charAt(i-1)) - Integer.valueOf(s.charAt(i+1));
String v = Integer.toString(val);
s = before + v + after;
}
}
return Integer.valueOf(s);
}
}
ㅈㄴ길게 썼는데...안된거 실환가요ㅠ
차분하게..stack을 써봤는데 실패하고 루션이를 봣읍니다^^
class Solution {
public int calculate(String s) {
if (s == null || s.isEmpty()) return 0;
int len = s.length();
Stack<Integer> stack = new Stack<Integer>();
int currentNumber = 0;
char operation = '+';
for (int i = 0; i < len; i++) {
char currentChar = s.charAt(i);
if (Character.isDigit(currentChar)) {
currentNumber = (currentNumber * 10) + (currentChar - '0');
}
if (!Character.isDigit(currentChar) && !Character.isWhitespace(currentChar) || i == len - 1) {
if (operation == '-') {
stack.push(-currentNumber);
}
else if (operation == '+') {
stack.push(currentNumber);
}
else if (operation == '*') {
stack.push(stack.pop() * currentNumber);
}
else if (operation == '/') {
stack.push(stack.pop() / currentNumber);
}
operation = currentChar;
currentNumber = 0;
}
}
int result = 0;
while (!stack.isEmpty()) {
result += stack.pop();
}
return result;
}
}
Runtime: 9 ms, faster than 69.76% of Java online submissions for Basic Calculator II.
Memory Usage: 39 MB, less than 77.02% of Java online submissions for Basic Calculator II.