Buttercola: Zenefits: Infix expression
Understand the problem: The problem looks complicated to implement, actually could be memorized in a template way. If the token is a number, then push it to the num stack. If the token is a operator, there are 5 cases to consider: 1. If the opStack is empty -- push into opStack -- If the top is '(', then push the token into opStack. -- Else (which means has higher or equal precedence), consume the stack by doing one computation. 3. If the token is * or / -- If the top is '(', push the token into opStack -- Else if top has lower precedence ( + or -), push the token into opStack. -- Else if the top has equal precedence (* or /), consume the stack by doing one computation. 4. If the token is ( -- Push into opStack -- Doing computations until we see the '(' in the opStack. Code (Java): public class Solution { public int calculate(String s) { if (s == null || s.length() == 0) { return 0; } // parse the string String delim = "[ ]+"; s = s.Read full article from Buttercola: Zenefits: Infix expression
No comments:
Post a Comment