Leetcode20 - Valid Parentheses

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.

第一反应是用栈,然后将左括号入栈,右括号出栈,遍历结束后看看是不是栈空了。
问题仍旧是各种边界条件..

public class Solution {
public boolean isValid(String s) {      
       Stack stack = new Stack();
       stack.push(s.charAt(0));
       for(int i=1;i

优化:
这些判断就是一个匹配功能,可以把两个字符是不是匹配单独提出来,再利用栈匹配就行,匹配就出栈,最后栈不为空就是整个字串无法匹配
所以一个更加减少错误的方法就是把这些类似的功能用一个函数操作处理。
但是由于频繁的函数调用,导致时间效率不如第一个。但是第一个的方法更容易出错。

public boolean isValid2(String s) { 
         Stack stack = new Stack();
           stack.push(s.charAt(0));
           for(int i=1;i

你可能感兴趣的:(java)