题目链接:
题目:
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
题目分析:
给定一组字符串,判断是不是有效的括号。
解题思路:
多开一个字符数组 temp,存储还没有匹配的括号。只要括号没有匹配,就放进这个数组里,如果下一个括号和该字符数组的最后一位进行了匹配,那么字符数组的最后一位去掉(相当于下标向前移动一位)。最后只要判断,是不是这个下标小于0,如果小于0,则说明是有效的true。
例子:{[]},先将第0位存进去 {,temp 的下标 ind = 0
然后开始从原字符串的第 1 位开始,发现是 [,所以继续存进 temp 里,ind = 1。
当第 2 位时,是 ] ,则判断 temp 的最后一位是 [,可以匹配,所以temp 的下标向前一位,ind = 0;
到第 3 位时,时 },判断temp 的最后一位是 {,可以匹配,所以temp 的下标向前一位,ind = -1。
退出循环,判断 ind 是否小于 0,是,所以是有效的括号。
其中有一个问题,假如在循环过程中,ind就小于0了,那么就相当于 temp里没存放,那么此时,无论原字符串的下一位是什么,都直接存放进 temp,保证temp里有可以判断比较的。
而在题目说到,空的字符串也是有效的,所以我们一开始判断原字符串的长度,如果==0,说明返回true 。
而且因为要匹配,所以如果长度不是偶数的话,那一定不是有效的。
AC代码:
class Solution {
public:
bool isValid(string s) {
int len = s.length();
if(len==0)
return true;
if(len%2 != 0)
return false;
int index = 0;
char temp[len+10];
temp[index] = s[0];
for(int i = 1;i < len;i++)
{
if(index < 0)
{
index = 0;
temp[0] = s[i];
continue;
}
if(s[i]==')' && temp[index]=='(')
{
--index;
continue;
}
if(s[i]==']' && temp[index]=='[')
{
--index;
continue;
}
if(s[i]=='}' && temp[index]=='{')
{
--index;
continue;
}
temp[++index] = s[i];
}
if(index < 0)
return true;
else
return false;
}
};