原题链接
字符配对问题,栈结构的典型应用
直接判断方法:
class Solution {
public:
bool isValid(string s) {
if(s.empty())//假定空字符串是有效的
return true;
stack<int> va;
int len=s.size();
for(int i=0;i<len;i++)
{
if(!va.empty()&&((va.top()=='('&&s[i]==')')
||(va.top()=='['&&s[i]==']')
||(va.top()=='{'&&s[i]=='}')))//配对成功出栈
va.pop();
else
va.push(s[i]);//配对不成功入栈
}
if(va.empty())//如果栈空则字符串有效
return true;
else
return false;
}
};
运用哈希表的方法
class Solution {
public:
bool isValid(string s) {
if(s.empty())
return true;
unordered_map<char,char> m={{')','('},
{']','['},
{'}','{'}};
stack<int> va;
int len=s.size();
for(int i=0;i<len;i++)
{
if(!va.empty()&&va.top()==m[s[i]])
va.pop();
else
va.push(s[i]);
}
if(va.empty())
return true;
else
return false;
}
};
遇到的问题:
从理论上来说,哈希表的方法的时间复杂度应该更小,但是结果恰恰相反