[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 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解