您的位置:首页 > 编程语言

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

2017-08-09 23:06 393 查看
【题目】

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;

}
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: