题目:Valid Parentheses 有效的括号
难度:简单
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
题意解析:
给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
解题思路一:
依次遍历这个字符串,然后将遍历过得存在一个数组中,当遇到有两个相连的对称的括号时,比如(),[],{}这是就让数组的索引-2,直到最后,如果字符串合格的话,最后的索引值应该就是小于0的。
public boolean isValid(String s) {
int len = s.length();
if (len % 2 == 1)
return false;
if (len == 0)
return true;
char[] chars = new char[len];
int index = 0;
for (int i = 0; i < len; i++) {
chars[index] = s.charAt(i);
if (index > 0){
if ((chars[index] == ')' && chars[index-1] == '(') || (chars[index] == ']' && chars[index-1] == '[') || (chars[index] == '}' && chars[index-1] == '{')){
index -= 2;
}
}
if (i < len-1)
index++;
}
return index<0;
}
时间复杂度:O(n)
提交代码之后:
Runtime: 0 ms, faster than 100.00% of Java online submissions for Valid Parentheses.
Memory Usage: 35.5 MB, less than 37.12% of Java online submissions for Valid Parentheses.