您的位置:首页 > 其它

[Leetcode 20] 20 Valid Parentheses

2013-05-19 04:16 302 查看
Problem:

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.

Analysis:

Use a stack to help. If the element is '(', '[', '{', push it onto stack. If the element is ')', ']', '}', pop one element from stack and see if they match with each other. If not match, then return false;

Other cases may cause false result are: 1. Meet with ')', ']', '}', but the stack is empty; 2. The string has been processed, but the stack is not empty.

The time complexity is O(n), the space complexity is O(n) in worst case, O(1) in best case;

Code:

public class Solution {
public boolean isValid(String s) {
// Start typing your Java solution below
// DO NOT write main() function
char[] stack = new char[100];
int tos = 0;
char tmp;

for (int i=0; i<s.length(); ++i) {
tmp = s.charAt(i);
switch(tmp) {
case '(': case '[': case '{': stack[tos++] = tmp; break;
case ')':
if (tos==0 || stack[--tos]!='(')
return false;
break;
case '}':
if (tos==0 || stack[--tos]!='{')
return false;
break;
case ']':
if (tos==0 || stack[--tos]!='[')
return false;
break;
}
}

if (tos != 0)
return false;
else
return true;
}
}


View Code

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