Showing posts with label Stack. Show all posts
Showing posts with label Stack. Show all posts
Sunday, August 30, 2015
Wednesday, August 12, 2015
LeetCode [255] Verify Preorder Sequence in Binary Search Tree
Monday, July 27, 2015
Tuesday, July 7, 2015
LeetCode [225] Implement Stack using Queues
[1] https://leetcode.com/problems/implement-stack-using-queues/
OJ
LeetCode [227] Basic Calculator II
227. Basic Calculator II
Medium
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers,
+, -, *, /operators and empty spaces . The integer division should truncate toward zero.
Example 1:
Input: "3+2*2" Output: 7
Example 2:
Input: " 3/2 " Output: 1
Example 3:
Input: " 3+5 / 2 " Output: 5
Note:
- You may assume that the given expression is always valid.
- Do not use the
evalbuilt-in library function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | //C++: stack 36ms class Solution { public: int calculate(string s) { stack<int> nums; stack<char> ops; int lhs = 0, rhs = 0, n = s.size(); for(int i=0; i<n; ++i){ if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/'){ ops.push(s[i]); }else if(s[i]!=' '){ rhs = rhs*10 + s[i] - '0'; if(i==n-1 || !isdigit(s[i+1])){ if(ops.empty() || ops.top()=='+' || ops.top()=='-'){ nums.push(rhs); }else{ while(!ops.empty()&&(ops.top()=='*'||ops.top()=='/')){ char op = ops.top(); ops.pop(); lhs = nums.top(); nums.pop(); rhs = (op=='*')?lhs*rhs:lhs/rhs; nums.push(rhs); } } rhs = 0; } } } lhs = 0; while(!ops.empty()){ rhs = nums.top(); nums.pop(); char op = ops.top(); ops.pop(); lhs = (op=='+')?lhs+rhs:lhs-rhs; } return lhs+nums.top(); } }; ]]></script> <script class="brush: js" type="syntaxhighlighter"><![CDATA[ //C++: 16ms class Solution { public: int calculate(string s) { s += "+"; int n = s.size(), i = 0, val = 0, prev = 0, cur = 0; char op = '+'; while(i<n){ if(isdigit(s[i])){ cur = cur*10+s[i++]-'0'; }else if(s[i]!=' '){ if(op=='+'){ val = val+cur; prev = cur; }else if(op=='-'){ val = val-cur; prev = -cur; }else if(op=='*'){ val = val-prev+prev*cur; prev = prev*cur; }else if(op=='/'){ val = val-prev+prev/cur; prev = prev/cur; } op = s[i++]; cur = 0; }else{ i++; } } return val; } }; ]]></script> <script class="brush: js" type="syntaxhighlighter"><![CDATA[ //C++: 16ms class Solution { public: int calculate(string s) { int res = 0, lhs = 0, rhs = 0, n = s.size(); char op = '+'; for(int i=0; i<n; ++i){ if(isdigit(s[i])){ rhs = rhs*10 + s[i] - '0'; if(i==n-1||!isdigit(s[i+1])){ switch(op){ case '+': lhs += rhs; break; case '-': lhs -= rhs; break; case '*': lhs *= rhs; break; case '/': lhs /= rhs; break; } rhs = 0; } }else if(s[i]!=' '){ if(s[i]=='+'||s[i]=='-'){ res += lhs; lhs = 0; } op = s[i]; } } return res + lhs; } }; class Solution { public: int calculate(string s) { int sz = s.size(); int i = 0; int lhs = 0; int prv = 0; char op = '+'; while(i<sz){ if(s[i]==' '){i++; continue;} int rhs = 0; while(i<sz && isdigit(s[i])){ rhs = rhs*10+(s[i]-'0'); i++; } switch(op){ case '+': lhs += rhs; prv = rhs; break; case '-': lhs -= rhs; prv = (-1)*rhs; break; case '*': lhs -= prv; lhs += prv*rhs; prv = prv*rhs; break; case '/': lhs -= prv; lhs += prv/rhs; prv = prv/rhs; break; default:break; } if(i<sz) op = s[i++]; } return lhs; } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | class Solution { public int calculate(String s) { Stack<Integer> nums = new Stack<>(); Stack<Character> ops = new Stack<>(); int v = 0; boolean hasV = false; s += '+'; for(char c:s.toCharArray()){ if(c==' ') continue; else if(Character.isDigit(c)){ v = v*10 + c - '0'; hasV = true; }else{//'+', '-' if(hasV) nums.push(v); v = 0; hasV = false; while(!ops.empty() && precedence(ops.peek())>=precedence(c)) evaluate(nums, ops); ops.push(c); } } return nums.pop(); } int precedence(char op){ switch(op){ case '+' : return 0; case '-' : return 0; case '*' : return 1; case '/' : return 1; default: return -2; } } void evaluate(Stack<Integer> nums, Stack<Character> ops){ int r = nums.pop(); int l = nums.pop(); char op = ops.pop(); int result = 0; switch (op) { case '+' : result = l+r; break; case '-' : result = l-r; break; case '*' : result = l*r; break; case '/' : result = l/r; break; default: break; } nums.push(result); } } |
LeetCode [224] Basic Calculator
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 .
Example 1:
Input: "1 + 1" Output: 2
Example 2:
Input: " 2-1 + 2 " Output: 3
Example 3:
Input: "(1+(4+5+2)-3)+(6+8)" Output: 23Note:
- You may assume that the given expression is always valid.
- Do not use the
evalbuilt-in library function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | class Solution { stack<int> ops, nums; public: int calculate(string s) { int lhs = 0, rhs = 0, sign = 1; for(auto c:s){ if(isdigit(c)){ rhs = rhs*10+(c-'0'); }else{ lhs += sign * rhs; rhs = 0; if(c=='+') sign = 1; else if(c=='-') sign = -1; else if(c=='('){ ops.push(sign); nums.push(lhs); sign = 1; lhs = 0; }else if(c==')'){ lhs = nums.top() + ops.top()*lhs; nums.pop(); ops.pop(); } } } return lhs + sign*rhs; } }; class Solution { public: int calculate(string s) { stack<int> nums; stack<char> ops; int i = 0, n = s.size(); while(i<n){ if(s[i]==' '){ while(i<n && s[i]==' ') ++i; }else if(s[i]=='('||s[i]=='+'||s[i]=='-'){ ops.push(s[i++]); }else{ int rhs = 0; if(s[i]>='0' && s[i]<='9'){ while(i<n && s[i]>='0' && s[i]<='9') rhs = rhs*10+(s[i++]-'0'); }else{//')' ++i; rhs = nums.top(); nums.pop(); ops.pop();//pop '(' } while(!ops.empty() && ops.top()!='('){ int lhs = nums.top(); nums.pop(); switch(ops.top()){ case '+': rhs = lhs + rhs; break; case '-': rhs = lhs - rhs; break; } ops.pop(); } nums.push(rhs); } } return nums.top(); } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | class Solution { public int calculate(String s) { Stack<Integer> nums = new Stack<>(); Stack<Character> ops = new Stack<>(); int v = 0; boolean hasV = false; s += '+'; for(char c:s.toCharArray()){ if(c==' ') continue; else if(Character.isDigit(c)){ v = v*10 + c - '0'; hasV = true; }else if(c=='('){ ops.push(c); }else if(c==')'){ if(hasV) nums.push(v); v = 0; hasV = false; while(!ops.empty() && ops.peek()!='(') evaluate(nums, ops); ops.pop();//pop '(' }else{//'+', '-' if(hasV) nums.push(v); v = 0; hasV = false; if(!ops.empty() && precedence(ops.peek())>=precedence(c)) evaluate(nums, ops); ops.push(c); } } return nums.pop(); } int precedence(char op){ switch(op){ case '(' : return -1; case '+' : return 0; case '-' : return 0; default: return -2; } } void evaluate(Stack<Integer> nums, Stack<Character> ops){ int r = nums.pop(); int l = nums.pop(); char op = ops.pop(); int result = 0; switch (op) { case '+' : result = l+r; break; case '-' : result = l-r; break; default: break; } nums.push(result); } } |
Tuesday, February 10, 2015
LeetCode [173] Binary Search Tree Iterator
173. Binary Search Tree Iterator
Medium
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Example:

BSTIterator iterator = new BSTIterator(root); iterator.next(); // return 3 iterator.next(); // return 7 iterator.hasNext(); // return true iterator.next(); // return 9 iterator.hasNext(); // return true iterator.next(); // return 15 iterator.hasNext(); // return true iterator.next(); // return 20 iterator.hasNext(); // return false
Note:
next()andhasNext()should run in average O(1) time and uses O(h) memory, where h is the height of the tree.- You may assume that
next()call will always be valid, that is, there will be at least a next smallest number in the BST whennext()is called.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class BSTIterator { stack<TreeNode*> stk; public: BSTIterator(TreeNode *root) { TreeNode *p = root; while(p){ stk.push(p); p = p->left; } } /** @return whether we have a next smallest number */ bool hasNext() { return !stk.empty(); } /** @return the next smallest number */ int next() { TreeNode* node = stk.top(); stk.pop(); TreeNode* p = node->right; while(p){ stk.push(p); p = p->left; } return node->val; } }; /** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */ /** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */ |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class BSTIterator { Stack<Integer> stk = new Stack(); public void build(TreeNode node){ if(node==null) return; build(node.right); stk.push(node.val); build(node.left); } public BSTIterator(TreeNode root) { build(root); } /** @return the next smallest number */ public int next() { return stk.pop(); } /** @return whether we have a next smallest number */ public boolean hasNext() { return !stk.isEmpty(); } } /** * Your BSTIterator object will be instantiated and called as such: * BSTIterator obj = new BSTIterator(root); * int param_1 = obj.next(); * boolean param_2 = obj.hasNext(); */ |
LeetCode [150] Evaluate Reverse Polish Notation
150. Evaluate Reverse Polish Notation
Medium
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Note:
- Division between two integers should truncate toward zero.
- The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.
Example 1:
Input: ["2", "1", "+", "3", "*"] Output: 9 Explanation: ((2 + 1) * 3) = 9
Example 2:
Input: ["4", "13", "5", "/", "+"] Output: 6 Explanation: (4 + (13 / 5)) = 6
Example 3:
Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"] Output: 22 Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 = ((10 * (6 / (12 * -11))) + 17) + 5 = ((10 * (6 / -132)) + 17) + 5 = ((10 * 0) + 17) + 5 = (0 + 17) + 5 = 17 + 5 = 22
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | class Solution { public: int evalRPN(vector<string>& tokens) { stack<int> stk; int n = tokens.size(); for(int i=0; i<n; ++i){ string s = tokens[i]; if(s=="+"||s=="-"||s=="*"||s=="/"){ int rhs = stk.top(); stk.pop(); int lhs = stk.top(); stk.pop(); int res; if(s=="+") res = lhs+rhs; else if(s=="-") res = lhs-rhs; else if(s=="*") res = lhs*rhs; else if(s=="/") res = lhs/rhs; stk.push(res); }else{ stk.push(stoi(s)); } } return stk.top(); } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class Solution { public int evalRPN(String[] tokens) { Stack<Integer> stk = new Stack<>(); for(String s : tokens){ if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")){ int b = stk.pop(); int a = stk.pop(); int r = 0; if(s.equals("+")) r = a+b; else if(s.equals("-")) r = a-b; else if(s.equals("*")) r = a*b; else r=a/b; stk.add(r); }else{ stk.push(Integer.parseInt(s)); } } return stk.pop(); } } |
Subscribe to:
Posts (Atom)