思路就是用一个栈来存储分数,剩下的就是对栈的操作了。
class Solution {
public int calPoints(String[] ops) {
Stack<Integer> stack = new Stack<>();
int sum = 0;
for(int i = 0;i<ops.length;i++){
String tmp = ops[i];
if(tmp=="C"){
int a = stack.pop();
sum -= a;
}else if(tmp=="D"){
int b = stack.peek()*2;
stack.push(b);
sum += b;
}else if(tmp=="+"){
int c = stack.pop();
int d = stack.pop();
int e = c+d;
sum += e;
stack.push(d);
stack.push(c);
stack.push(e);
}else{
int res = myInt(tmp);
stack.push(res);
sum += res;
}
}
return sum;
}
public static int myInt(String s){
int result = 0;
if(s.charAt(0)=='-'){
for(int i=1;i<s.length();i++){
result = result*10 + (int)(s.charAt(i)-'0');
}
result = result*(-1);
}else{
for(int i =0;i<s.length();i++){
result = result*10 + (int)(s.charAt(i)-'0');
}
}
return result;
}
}
当OJ说结果错误时,我的世界是崩塌的,明明IDE没问题的呀。原来是对于字符串的比较要用equals,IDE应该是重载了==。还是po个正确的吧。
class Solution {
public int calPoints(String[] ops) {
Stack<Integer> stack = new Stack<>();
int sum = 0;
for(int i = 0;i<ops.length;i++){
String tmp = ops[i];
if(tmp.equals("C")){
int a = stack.pop();
sum -= a;
}else if(tmp.equals("D")){
int b = stack.peek()*2;
stack.push(b);
sum += b;
}else if(tmp.equals("+")){
int c = stack.pop();
int d = stack.pop();
int e = c+d;
sum += e;
stack.push(d);
stack.push(c);
stack.push(e);
}else{
int res = myInt(tmp);
stack.push(res);
sum += res;
}
}
return sum;
}
public static int myInt(String s){
int result = 0;
if(s.charAt(0)=='-'){
for(int i=1;i<s.length();i++){
result = result*10 + (int)(s.charAt(i)-'0');
}
result = result*(-1);
}else{
for(int i =0;i<s.length();i++){
result = result*10 + (int)(s.charAt(i)-'0');
}
}
return result;
}
}
其实也不用自己写个myInt。可以用Integer.valueOf(str)或者是Integer.valueOf(str).intValue()
用自己写的呢,速度快击败100%,用现成的也可以,慢一点,击败91%。
来源:CSDN
作者:爱打篮球的憨憨
链接:https://blog.csdn.net/xiaobailaji/article/details/104754866