给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
c++:
c++ stack容器介绍:https://www.cnblogs.com/hdk1993/p/5809161.html
执行用时 : 12 ms, 在Valid Parentheses的C++提交中击败了13.39% 的用户
内存消耗 : 8.9 MB, 在Valid Parentheses的C++提交中击败了0.93% 的用户
class Solution {
public:
bool isValid(string s) {
if(s.length() < 1) //empty
return true;
stack<char> s1;
char c;
for(int i=0; i<s.length(); i++) {
if(s[i] == '(' || s[i] == '[' || s[i] == '{')
s1.push(s[i]);
else {
if(s1.empty())
return false;
c = s1.top();
s1.pop();
if(c == '(' && s[i]==')')
continue;
else if(c == '[' && s[i]==']')
continue;
else if(c == '{' && s[i]=='}')
continue;
else
return false;
}
}
if(s1.empty())
return true;
else
return false;
}
};
c++:
执行用时 : 16 ms, 在Valid Parentheses的C++提交中击败了10.26% 的用户
内存消耗 : 8.9 MB, 在Valid Parentheses的C++提交中击败了0.93% 的用户
#include <stack>
class Solution {
public:
bool isValid(string s) {
int i=s.size();
stack <char>stk;
int j;
for(j=0;j<i;j++){
switch(s[j]){ //遇到左括号进栈,遇到右括号与栈顶元素对比
case'{':
case'[':
case'(':stk.push(s[j]);break;
case'}':if(!stk.empty()&&'{'==stk.top()){stk.pop();break;} //不匹配时return false
else return false;
case']':if(!stk.empty()&&'['==stk.top()){stk.pop();break;}
else return false;
case')':if(!stk.empty()&&'('==stk.top()){stk.pop();break;}
else return false;
}
}
if(!stk.empty())return false; //栈非空时证明有单独的左括号,return false
else return true; //当s为空时栈也为空,return true
}
};
【后记】
1.最开始忽略了先遇到右括号(此时栈空无法比较)这种情况,也忽略了字符串为空这种情况
2.用C++好爽啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊