您的位置:首页 > 其它

Leet Code 20 Valid Parentheses

2015-09-12 03:08 323 查看
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 boolean isValid(String s) {
int length = s.length();
if(length % 2 == 1)
{
return false;
}

HashMap<Character, Character> map = new HashMap<Character, Character>();
map.put('(', ')');
map.put('{', '}');
map.put('[', ']');

Stack<Character> stack = new Stack<Character>();
if(map.containsKey(s.charAt(0)))
stack.push(s.charAt(0));
else
return false;

for(int i = 1; i < length; i ++)
{
char ch = s.charAt(i);
if(!stack.isEmpty() && (map.get(stack.peek()) == ch))
{
stack.pop();
}
else if(map.containsKey(ch))
stack.push(ch);
else return false;

if(!stack.isEmpty() && (stack.size() > length - i))
return false;
}

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