算法练习——有效括号

2022/4/21 22:12:39

本文主要是介绍算法练习——有效括号,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

使用栈,先将左括号入栈,然后遍历字符串,在对括号进行匹配

给定一个只包括 '('')''{''}''['']' 的字符串 s ,判断字符串是否有效。

//有效的括号
#include<iostream>
#include<stack>
#include<string>
#include<vector>
using namespace std;

class Solution {
public:
    bool isValid(string s);
};

bool Solution::isValid(string s) {
    vector<char> left;
    char right;
    int n = s.length();
    int left_count = 0;
    if (n % 2 == 0 && s[0] != '}' && s[0] != ']' && s[0] != ')'){
        for (int i = 0; i < n; i++) {
            if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
                left.push_back(s[i]);
            }
            else
            {
                right = s[i];
                int num = left.size();
                char temp = left.at(num - 1);
                if (right == ')' && temp == '(')
                {
                    left.pop_back();
                }
                else if (right == '}' && temp == '{')
                {
                    left.pop_back();
                }
                else if (right == ']' && temp == '[')
                {
                    left.pop_back();
                }
                else return 0;
            }
        }
        int count = left.size();
        if (count == 0) return 1;
        else
        {
            return 0;
        }
    }
    else
    {
        return 0;
    }
}

int main() {
    string s;
    cin >> s;
    Solution so;
    cout << so.isValid(s) << endl;
    return 0;
}

 



这篇关于算法练习——有效括号的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程