Leetcode 20. 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.

二、题目分析:

1.符合题意的形式还有:嵌套形式:{ [ ( ) ] } ,{ ( [] ) [ ] }

2.本题的经典在使用了 栈 的数据结构,先进后出,内层括号首先匹配,外层再进行匹配。

3.解题思路:

  遍历所有输入的全部括号,

    若是左括号,则压入栈中。

    若是右括号,则和栈顶元素进行匹配。匹配成功则,则弹出栈顶元素,否则返回false,程序结束。

三、代码:

public class Solution {
    
    public boolean isValid(String s) {
        Stack<Character> stack=new Stack<Character>();
        for(int i=0;i<s.length();i++){
            char c=s.charAt(i);
            if(c!='}' && c!=']' && c!=')'){
                stack.push(c);
            }else{
                if(stack.isEmpty())
                   return false; 
                char topChar=stack.peek();
                switch(c){
                    case ')':
                        if(topChar=='('){
                            stack.pop();
                        }else{
                            return false;
                        }
                        break;
                    case ']':
                        if(topChar=='['){
                            stack.pop();
                        }else{
                            return false;
                        }
                        break; 
                    case '}':
                        if(topChar=='{'){
                            stack.pop();
                        }else{
                            return false;
                        }
                        break;
            }
        }
    }
            if(stack.isEmpty()){
                 return true;
            }else{
                return false;
            }
   
}
}        
原文地址:https://www.cnblogs.com/lyr2015/p/6340361.html