20. Valid Parentheses(java)

来源:互联网 发布:音乐盒淘宝 编辑:程序博客网 时间:2024/05/29 13:16

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.

思路:对字符串S中的每一个字符i,如果i是左括号,则入栈。如果i是右括号,首先判断stack是否为空,空则说明没有左括号,直接返回false,如果非空则弹出栈顶的字符top来作比较,如果相匹配,继续取S中的下一个字符;如果不匹配,直接返回false。当遍历完字符串S后,判断stack中是否还有字符没有得到匹配,如果stack不为空,返回false。

public class Solution {    public boolean isValid(String s) {        if(s.length()==0||s.length()==1) return false;        Stack<Character> charStack=new Stack<Character>();        for(int i=0;i<s.length();i++){            if(s.charAt(i)=='('||s.charAt(i)=='{'||s.charAt(i)=='[')            {                charStack.push(s.charAt(i));            }            else{                if(charStack.size()==0){                    return false;                }                char top=charStack.pop();                if(s.charAt(i)==')'){                    if(top!='(') return false;                }                else if(s.charAt(i)==']'){                    if(top!='[') return false;                }                if(s.charAt(i)=='}'){                    if(top!='{') return false;                }                }        }        return charStack.size()==0;    }}


原创粉丝点击