`
zhang_xzhi_xjtu
  • 浏览: 538414 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

[leetcode] ValidParentheses

阅读更多
package leetcode;

import java.util.Stack;

/**
* <pre>
* Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
*
* The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
* </pre>
*/
public class ValidParentheses {

    public class Solution2 {
        public boolean isValid(String s) {
            Stack<Integer> stack = new Stack<Integer>();
            stack.push(0);
            for (int i = 0; i < s.length(); i++) {
                int c = s.charAt(i);
                if (stack.peek() + 1 == c || stack.peek() + 2 == c)
                    stack.pop();
                else
                    stack.push(c);
            }
            return stack.size() == 1;
        }
    }

    public class Solution {

        public boolean isValid(String s) {
            Stack<Integer> stack = new Stack<Integer>();
            for (int i = 0; i < s.length(); i++) {
                int c = s.charAt(i);
                if (stack.isEmpty()) {
                    stack.push(c);
                    continue;
                }
                int tem = stack.peek();
                if (tem + 1 == c || tem + 2 == c)
                    stack.pop();
                else
                    stack.push(c);
            }
            return stack.isEmpty();
        }
    }

}
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics