给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: “()”
输出: true
示例 2:
输入: “()[]{}”
输出: true
示例 3:
输入: “(]”
输出: false
示例 4:
输入: “([)]”
输出: false
示例 5:
输入: “{[]}”
输出: true
方法一:利用栈
class Solution {
public:
bool isValid(string s) {
stack<char> result;
int n = s.size();
if (n == 0) return true;
for (int i = 0; i < n; i++)
{
if (result.empty())
result.push(s[i]);
else if (result.top() == '(' && s[i] == ')' ||
result.top() == '[' && s[i] == ']' ||
result.top() == '{' && s[i] == '}')
result.pop();
else
result.push(s[i]);
}
return result.empty();
}
};
此方法转自https://blog.csdn.net/qq_38331894/article/details/80297401
方法二:方法都是配对类似栈,但为纯字符串操作,此方法较为费时
public boolean isValid(String s) {
//假如长度是1或者不为偶数
if (s.length() < 2 || s.length() % 2 != 0) {
if (s.isEmpty()) {
return true;
}
else {
return false;
}
}
int count = 0;
int length = s.length();
//循环替换,最大次数为s.length()/2
while (count < length / 2) {
s = s.replace("{}", "").replace("[]", "").replace("()", "");
count++;
}
//假如循环替换完,还有值,那么肯定就不是对称结构
if (s.length() > 0) {
return false;
}
else {
return true;
}
}
此方法转自https://blog.csdn.net/qq_38455201/article/details/82887217