您的位置:首页 > 其它

[LeetCode]224. Basic Calculator

2016-03-04 22:29 232 查看

Problem Description

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .

You may assume that the given expression is always valid.

[]https://leetcode.com/problems/basic-calculator/]

思路

自己的思路是利用递归迭代。。TLE了。。。。

看了看大神的思路,,用个栈就可以了。。。

[]https://leetcode.com/discuss/39553/iterative-java-solution-with-stack]

Code

TLE版

package q224;

public class Solution_TLE {

public static int calculate(String s) {
if(s.length()<1) return 0;
int ans = 0;
String tmp = "";
String newtmp = "";
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == '+') {
ans = ans + Integer.parseInt(tmp);
tmp = "";
} else if (s.charAt(i) == '-') {
ans = ans - Integer.parseInt(tmp);
tmp = "";
} else if (s.charAt(i) == ' ') {
continue;
} else if (s.charAt(i) == ')') {
int mark = 1;
i--;
while (i >= 0 && mark != 0) {
if (s.charAt(i) == ')')
mark++;
if (s.charAt(i) == '(')
mark--;
newtmp = s.charAt(i) + newtmp;
i--;
}
if(tmp=="") tmp=calculate(newtmp.substring(1))+"";
i++;
newtmp="";
} else if (s.charAt(i) == '(') {
continue;
} else {
tmp = s.charAt(i) + tmp;
}
}

if (tmp.length() > 0)
ans = ans + Integer.parseInt(tmp);
return ans;
}

//  public static void main(String[] args) {
//      System.out.println(calculate("(1+(4+5+2)-3)+(6+8)"));
//  }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode