美文网首页
C++ 判断是否成对出现的括号

C++ 判断是否成对出现的括号

作者: FredricZhu | 来源:发表于2020-12-01 13:33 被阅读0次
#include <iostream>
using namespace std;
#include <set>
#include <string>

// isPairedPareshis 判断是否成对出现的括号 str 输入的字符串
bool isPairedPareshis(std::string str) {
    std::string::iterator it;
    // 构建multiset对象,用于存储char字符
    std::multiset<char>  s;
    
    // 标志位,是否是成对出现
    bool isPaired = true;

    std::multiset<char>::iterator sit;
    // 逐字符遍历
    for(it=str.begin();it!=str.end(); it++) {
        // 遇到左括号进行插入
        if((*it == '(') || (*it == '[')) {
            s.insert(*it);
            // 如果遇到右括号
        }else if(*it==')') {
            // 查找set里面是否有左括号,如果没有,说明挂了
            sit = s.find('(');
            if(sit == s.end()) {
                isPaired = false;
                break;
                // 否则擦除掉左括号,重新开始配对
            }else {
                s.erase(sit);
            }
            // 如果遇到右中括号
        }else if(*it==']') {
            // 查找set里面是否有左中括号,如果没有,说明挂了
            sit = s.find('[');
            if(sit == s.end()) {
                isPaired = false;
                break;
                // 否则擦除掉左中括号,重新开始配对
            }else {
                 s.erase(sit);
            }
        }
    }
    // 如果完事儿容器里面还有元素,说明有元素没配对上
    if(s.size()>0) {
        isPaired = false;
    }
    return isPaired;
}

int main() {
    // 需要判断的字符串
    std::string str = "[()[]]";
  
    // 是否成对出现的括号
    bool isPaired = isPairedPareshis(str);
    // 打印输出结果
    std::cout << "是否成对的括号: " << isPaired << std::endl;
    std::cout << "请按任意键继续..." << std::endl;
    getchar();
    return 0;
}

程序输出如下,


图片.png

相关文章

网友评论

      本文标题:C++ 判断是否成对出现的括号

      本文链接:https://www.haomeiwen.com/subject/vbhswktx.html