【leetcode】第20题 Valid Parentheses 题目+解析+代码

来源:互联网 发布:杭州网络推广排名 编辑:程序博客网 时间:2024/06/05 06:58

【题目】

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) {char[] stack = new char[s.length()];int head = 0;char[] cs = s.toCharArray();                  for(int i=0;i<cs.length;i++){  switch(cs[i]) {case '{':case '[':case '(':stack[head] = cs[i];   
                                        head++;break;case '}':if(head == 0 || stack[head-1] != '{') return false;                                        head--;break;case ')':if(head == 0 || stack[head-1] != '(') return false;                                        head--;break;case ']':if(head == 0 || stack[head-1] != '[') return false;head--;                                        break;}}return head == 0;}}


 
原创粉丝点击