中级农民
- 积分
- 100
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-12-10
- 最后登录
- 1970-1-1
|
STACK
amazon oa 最新面试题
Validate statement
Given an input expression that can contain positive integers,
parenthesis or square brackets, return if the input is balanced. An
expression is considered balanced if it has the following form: (
expression ) OR [ expression ] and If expression is also balanced.
Input Format:
A string where characters could be either a number or ( ) [ ]
Output Format:
A boolean, true if the input is balanced, false otherwise.
Sample Input #1:
([5 2 ] 12 )
Sample Output #1:
true
Explanation:
The square brackets are correctly closed before the parenthesis
Sample Input #2:
40 [12 23 [4 5 ( 12 ) ) ]
Sample Output #2:
false
Explanation:
The second square bracket does not have a corresponding closing one, a
parenthesis appears instead.
Sample Input #3:
13 56 89 103
Sample Output #2:
true
Explanation:
The expression doesn't contain any ()[] and it is considered balanced.- public class ValidateStatement {
- static boolean isBalanced(String input) {
- if (input == null) {
- return true;
- }
- Stack<Character> stack = new Stack<Character>();
- Map<Character, Character> map = new HashMap<Character, Character>();
- map.put('(', ')');
- map.put('[', ']');
- for (int i = 0; i < input.length(); ++i) {
- char ch = input.charAt(i);
- if (ch == '(' || ch == '[') {
- stack.push(ch);
- } else if (!Character.isDigit(ch) && !Character.isWhitespace(ch)) {
- if (stack.isEmpty() || map.get(stack.peek()) == null
- || !stack.pop().equals(ch)) {
- return false;
- }
- }
- }
- return stack.isEmpty();
- }
- }
复制代码 |
|