给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()" 输出: true
示例 2:
输入: "()[]{}" 输出: true
示例 3:
输入: "(]" 输出: false
示例 4:
输入: "([)]" 输出: false
示例 5:
输入: "{[]}" 输出: true
C
bool isValid(char* s)
{
int n=strlen(s);
char* temp=(char*)malloc(sizeof(char)*(n+1)/2);
int k=0;
for(int i=0;i<n;i++)
{
if(s[i]=='(' || s[i]=='[' || s[i]=='{')
{
temp[k]=s[i];
k++;
}
else
{
if(k==0)
{
return false;
}
else
{
if(s[i]==')' && temp[k-1]!='(' || s[i]==']' && temp[k-1]!='[' || s[i]=='}' && temp[k-1]!='{' )
{
return false;
}
}
temp[k-1]='\0';
k--;
}
}
return strlen(temp)==0;
}
C++
class Solution {
public:
bool isValid(string s)
{
stack<char> temp;
int n=s.length();
for(int i=0;i<n;i++)
{
if(s[i]=='(' || s[i]=='[' || s[i]=='{')
{
temp.push(s[i]);
}
else
{
if(temp.empty())
{
return false;
}
else
{
if(s[i]==')' && temp.top()!='(' ||s[i]==']' && temp.top()!='[' || s[i]=='}' && temp.top()!='{')
{
return false;
}
temp.pop();
}
}
}
return temp.empty();
}
};
python
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
n=len(s)
temp=[]
for i in range(0,n):
if s[i]=='(' or s[i]=='[' or s[i]=='{':
temp.append(s[i])
else:
if len(temp)==0:
return False
elif s[i]==')' and temp[-1]!='(' or s[i]==']' and temp[-1]!='[' or s[i]=='}' and temp[-1]!='{':
return False
del temp[-1]
return len(temp)==0