题目链接: 有效的括号
有关题目
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
示例 1:
输入:s = "()"
输出:true
示例 2:
输入:s = "()[]{}"
输出:true
示例 3:
输入:s = "(]"
输出:false
示例 4:
输入:s = "([)]"
输出:false
示例 5:
输入:s = "{[]}"
输出:true
提示:
1 <= s.length <= 10^4
s 仅由括号 '()[]{}' 组成
题解
法一:字符间ASCII差值
class Solution {
public:
bool isValid(string s) {
int len = s.size();
if (len % 2 == 1) return false;
stack<char> stk;
for (char ch : s){
if (stk.empty()){
stk.push(ch);
} else if (ch - stk.top() == 1 || ch - stk.top() == 2) {
//查ASCII表可知,成对出现的括号之间,差值为1或者2;
stk.pop();
} else
stk.push(ch);
}
return stk.empty();
}
};
时间复杂度:O(N)
空间复杂度:O(N)
法二:栈
C
int pairs(char a){
if (a == ')') return '(';
if (a == ']') return '[';
if (a == '}') return '{';
return 0;
}
bool isValid(char * s){
int len = strlen(s);
if (len % 2 == 1) return false;
int stk[len], top = 0;
for (int i = 0; i < len; i++){
char ch = pairs(s[i]);//ascii码也可以用数字表示字符
if (ch){
if (top == 0 || stk[top - 1] != ch) return false;
top--;
} else {
stk[top++] = s[i];
}
}
return top == 0;
}
C++
代码一:不用哈希表
class Solution {
public:
bool isValid(string s) {
int n = s.length();
if (n % 2 == 1)//减枝
return false;
stack<char> st;
for (char ch : s)
{
if (ch == '(' || ch == '[' || ch == '{')
st.push(ch);
if (ch == ')')
{
if (!st.empty() && st.top() == '(')
st.pop();
else
return false;
}
if (ch == ']')
{
if (!st.empty() && st.top() == '[')
st.pop();
else
return false;
}
if (ch == '}')
{
if (!st.empty() && st.top() == '{')
st.pop();
else
return false;
}
}
if (!st.empty())
return false;
return true;
}
};
代码二:
使用哈希表
class Solution {
public:
bool isValid(string s) {
int n = s.length();
if (n % 2 == 1)
return false;
unordered_map<char,int> m {
{'(',1},
{'[',2},
{'{',3},
{')',4},
{']',5},
{'}',6}
};
stack<char> st;
for (char ch : s)
{
int flag = m[ch];
if (flag >= 1 && flag <= 3)
st.push(ch);
else if (!st.empty() && m[st.top()] == flag - 3)
st.pop();
else
return false;
}
return st.empty();
}
};
代码三:
使用哈希表
哈希表的键为右括号,值为相同类型的左括号
{')', '('},//)为键 (为值
{']', '['},
{'}', '{'}
class Solution {
public:
bool isValid(string s) {
int n = s.length();
if (n % 2 == 1)
return false;
unordered_map<char,char> pairs = {
{')', '('},
{']', '['},
{'}', '{'}
};
stack<char> stk;
for (char ch : s)
{
if (pairs.count(ch))//找到哈希表中ch键,即')',']','}',也就是右括号
{
if (stk.empty() || stk.top() != pairs[ch])//pairs[ch] 为值
return false;
//移除栈顶元素
stk.pop();
}
else
stk.push(ch);//在栈顶增加左括号
}
return stk.empty();
}
};