给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出 : true
以前做过一道类似的括号匹配,原题只涉及一种括号,相对容易处理。看到这道题的第一想法是用三个变量来处理。但是这样就会忽略一部分的错误情况。
eg:([)] 这样的样例还是会通过的。但是实际来看应该是错误的。后面改进了一次,就是判断sum的和值,但是又出了新的坑,证明这种方法是不太靠谱的。
//代码的大致思路很简单,就是先排除一些不可能的状态,然后遍历求权值。
class Solution {
public:
bool isValid(string s)
{
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
int len = s.length();
if (len % 2 == 1)
return false;
else if (len == 0)
return true;
else if (s[0] == ')' || s[0] == ']' || s[len - 1] == '[' || s[len - 1] == '('|| s[0] == '}' || s[len - 1]=='{')
return false;
for (int i = 0; i < len ; ++i)
{
if (s[i] == '(')
sum1++;
else if (s[i] == ')')
sum1--;
else if (s[i] == '[')
sum2++;
else if (s[i] == ']')
sum2--;
else if (s[i] == '{')
sum3++;
else if (s[i] == '}')
sum3--;
if (sum1 < 0 || sum2 < 0||sum3<0)
return false;
}
return true;
}
};
然后,有想了个办法,貌似比较靠谱一点。
用双指针,和(匹配的)只有两个位置,要么挨着要么在最后。
代码如下,时间复杂度也还好。
但是又踩雷了:"(([]){})"
bool isValid(string s)
{
int len = s.length();
if (len % 2 == 1)
return false;
else if (len == 0)
return true;
else if (s[0] == ')' || s[0] == ']' || s[len - 1]
== '[' || s[len - 1] == '(' || s[0] == '}' || s[len - 1] == '{')
return false;
int i = 0;
while (i < len / 2)
{
if (s[i] - s[len - 1 - i] == -1 || -2 == s[i] - s[len - 1 - i])
{
i++;
}
else if (s[i] - s[i + 1] == -1 || -2 == s[i] - s[i + 1])
{
i+=2;
}
else
{
return false;
}
}
return true;
}
官方:https://leetcode-cn.com/problems/valid-parentheses/submissions/
唉,想到了栈处理,但是还是没想到具体方法;
class Solution {
// Hash table that takes care of the mappings.
private HashMap<Character, Character> mappings;
// Initialize hash map with mappings. This simply makes the code easier to read.
public Solution() {
this.mappings = new HashMap<Character, Character>();
this.mappings.put(')', '(');
this.mappings.put('}', '{');
this.mappings.put(']', '[');
}
public boolean isValid(String s) {
// Initialize a stack to be used in the algorithm.
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
// If the current character is a closing bracket.
if (this.mappings.containsKey(c)) {
// Get the top element of the stack. If the stack is empty, set a dummy value of '#'
char topElement = stack.empty() ? '#' : stack.pop();
// If the mapping for this bracket doesn't match the stack's top element, return false.
if (topElement != this.mappings.get(c)) {
return false;
}
} else {
// If it was an opening bracket, push to the stack.
stack.push(c);
}
}
// If the stack still contains elements, then it is an invalid expression.
return stack.isEmpty();
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/valid-parentheses/solution/you-xiao-de-gua-hao-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。