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.
[code]
public class Solution {
public boolean isValid(String s) {
if(s==null || s.length()==0)return true;
Stack<Character> stack=new Stack<Character>();
HashMap <Character, Character> map=new HashMap<Character, Character>();
map.put(')', '(');
map.put(']', '[');
map.put('}', '{');
int i=0;
while( i<s.length() )
{
char c=s.charAt(i);
if( map.containsValue(c) )
{
stack.push(c);
}
else
{
if( stack.empty() || map.get(c)!=stack.pop() ) return false;
}
i++;
}
return stack.empty();
}
}
418




被折叠的 条评论
为什么被折叠?



