给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
总结:
考虑不全面,通过测试点进行修补程序,比较浪费时间
思路:
- 用栈
- 边界排除:字符数为奇数个返回false
- 遍历每一个字符:
- 若当前字符为左括号,则入栈;
- 若当前字符为右括号:没有左括号(即栈为空),返回false; 栈不为空但左右括号不匹配,false;
- 若当前字符为右括号且括号相匹配,则弹栈;
- 结束遍历后栈为空则返回true.
bool isValid(string s)
{
stack<char> st;
if(s.length()%2==1)
return false;
for(int i=0;i<s.length();i++)
{
if(s[i]=='('||s[i]=='['||s[i]=='{')
{
st.push(s[i]);
}
if(st.empty()&&(s[i]==')'||s[i]==']'||s[i]=='}'))
return false;
if(!st.empty())
{
if(s[i]==')'&&st.top()!='('||s[i]==']'&&st.top()!='['||s[i]=='}'&&st.top()!='{')
return false;
if(s[i]==')'&&st.top()=='('||s[i]==']'&&st.top()=='['||s[i]=='}'&&st.top()=='{')
st.pop();
}
}
return st.empty();
}
利用哈希表键值存储匹配
unordered_map<char,char> pairs
pairs.count() 返回匹配特定键的元素数量
bool isValid(string s)
{
stack<char> st;
if(s.length()%2==1)
return false;
unordered_map<char,char> pairs={
{')','('},
{']','['},
{'}','{'}
};
for(int i=0;i<s.length();i++)
{
if(pairs.count(s[i]))
{
if(st.empty()||pairs[s[i]]!=st.top())
return false;
st.pop();
}
else
{
st.push(s[i]);
}
}
return st.empty();
}