当前位置: 代码迷 >> 综合 >> leetcode 20. Valid Parentheses 括号匹配
  详细解决方案

leetcode 20. Valid Parentheses 括号匹配

热度:91   发布时间:2023-12-26 08:26:36.0

基于栈:

#include<iostream>
#include<stack>
#include<string>
using namespace std;class Solution {
public:bool isValid(string s) {stack<char> S;for (int i = 0; i<s.size(); ++i){switch (s[i]){case'(':S.push(s[i]); break;case'{':S.push(s[i]); break;case'[':S.push(s[i]); break;case')':if (S.empty() || S.top() != '(')return false;elseS.pop(); break;case ']':if (S.empty() || S.top() != '[')return false;elseS.pop(); break;case '}':if (S.empty() || S.top() != '{')return false;elseS.pop(); break;default:break;}}return S.empty();}
};int main()
{int N;cin >> N;string *a = new string[N]; //输入多组for (int i = 0; i<N; i++){a[i] = ""; //初始化cin >> a[i];}Solution solution;for (int i = 0; i<N; i++){if (solution.isValid(a[i]) == true)cout << "Yes" << endl;elsecout << "No" << endl;}system("pause");return 0;
}/*
bool isValid(string s) {stack<char> S;for(const auto& c : s){switch(c){case '{':  S.push('}'); break;case '[':  S.push(']'); break;case '(':  S.push(')'); break;default:if(S.size() == 0 || c != S.top()) return false;else S.pop();}}return S.size() == 0;
}
*/

 

基于队列:

 

  相关解决方案