题目:
给定一个只包括 ‘(‘,’)’,’{‘,’}’,’[‘,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。 注意空字符串可被认为是有效字符串。
解法:
栈的应用
如果当前字符串中字符为左括号则压入栈,如果为右括号则判断是否与栈顶字符是一对括号,是则继续并出栈,不是则字符串中字符入栈。
c++代码:
1 class Solution {
2 public:
3 bool isValid(string s) {
4 stack<char>The_Stack;
5 int i=0;
6 The_Stack.push('#');
7 while(i<s.size()) {
8 if((s[i]==')'&&The_Stack.top()=='(')||(s[i]==']'&&The_Stack.top()=='[')||(s[i]=='}'&&The_Stack.top()=='{')) {
9 i++;
10 The_Stack.pop();
11 }
12 else {
13 The_Stack.push(s[i]);
14 i++;
15 }
16 }
17 if(The_Stack.top()=='#')
18 return true;
19 return false;
20 }
21 };