一 题目
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()" Output: true
Example 2:
Input: "()[]{}" Output: true
Example 3:
Input: "(]" Output: false
Example 4:
Input: "([)]" Output: false
Example 5:
Input: "{[]}" Output: true
二 分析
题目要求判断字符串里面括号是否匹配,题目easy级别。
终于遇到一个看题目就知道怎么做的了,首先想到就是栈 ,遍历字符串,如果是左侧的括号就入栈,否则就出栈,与当前字符判断是否匹配。唯一注意的是边界条件.如“]”这种只有右侧没有左侧的。
public static void main(String[] args) {
System.out.println(isValid("]"));
System.out.println(isValid("()[]{}"));
System.out.println(isValid("(]"));
System.out.println(isValid("([)]"));
System.out.println(isValid("{[]}"));
}
public static boolean isValid(String s) {
Map<Character,Character> map = new HashMap();
map.put(')', '(');
map.put(']', '[');
map.put('}', '{');
Stack stack = new Stack();
if(s==""){
return true;
}
for(char c:s.toCharArray()){
if(c=='('||c=='['||c=='{'){
stack.push(c);
}
else {//coner case
if(stack.isEmpty()){
return false;
}
//rule
char pre = (char) stack.pop();
if(map.get(c)==null|| map.get(c)!=pre){
return false;
}
}
}
return stack.isEmpty();
}
Runtime: 2 ms, faster than 60.59% of Java online submissions for Valid Parentheses.
Memory Usage: 34.1 MB, less than 100.00% of Java online submissions for Valid Parentheses.
官网的solution也是stack,比我写的好。感兴趣的可以去官网在看看。
时间复杂度:O(N).
空间复杂度:O(N).