leetcode判断是否有效括号

题目

给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

解答

我个人想到最简单易懂的方法

class Solution {
    public boolean isValid(String s) {
   Stack<Character> stack = new Stack<Character>();

	
    for(Character c : s.toCharArray()){
       if((c==')' || c==']' || c=='}') && !stack.isEmpty()){
           if((stack.peek()=='('&&c==')') || (stack.peek()=='['&&c==']') || (stack.peek()=='{'&&c=='}')){
               stack.pop();
               continue;
            }
            return false;
       }
        stack.push(c);            
     }
    return stack.isEmpty();


    }
}
发布了26 篇原创文章 · 获赞 1 · 访问量 489

猜你喜欢

转载自blog.csdn.net/Vince_Wang1/article/details/103797808