Valid Parentheses

来源:互联网 发布:根据域名添加路由设置 编辑:程序博客网 时间:2024/06/16 06:20

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.

思路: 凡事有关括号的, 肯定用stack 是最直观简单的。
Using a stack to storage the left parentheses. If the input right parentheses is not the right one return false. At last need to check the stack empty.

易错点: 1. 右括号进来的话, 要先检查是否stack 空。  2.  最后一定要检查stack  是否为空。

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;                }                if(c == ')'){                    if(stack.pop() != '('){                        return false;                    }                }else if(c == ']'){                    if(stack.pop() != '['){                        return false;                    }                }else{                    if(stack.pop() != '{'){                        return false;                    }                }            }        }                if(!stack.isEmpty()){            return false;        }        return true;    }}


0 0
原创粉丝点击