如何在字符串中找到匹配的大括号对?

How to find the matching pair of braces in a string?(如何在字符串中找到匹配的大括号对?)

本文介绍了如何在字符串中找到匹配的大括号对?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个字符串 "(paid for) + (8 working hours) + (company rules)" .现在我想检查这个完整的字符串是否用括号括起来.基本上我想检查字符串是否是这样的:((付费)+(8个工作小时)+(公司规则))".如果它已经用括号括起来,那么我将保持原样,否则我会将括号应用于完整的字符串,以便输出为:((支付)+(8个工作小时)+(公司规则))" .通过计算括号的数量,我无法解决这个问题.

Suppose I have a string "(paid for) + (8 working hours) + (company rules)" . Now I want to check whether this complete string is surrounded with parentheses or not. Basically I want to check if the string is like this or not : "((paid for) + (8 working hours) + (company rules))". If it is already surrounded with parentheses, then I will leave it as it is, otherwise I will apply parentheses to the complete string so that the ouput is : "((paid for) + (8 working hours) + (company rules))" . By counting the number of parentheses, I am not able to solve this problem.

谁能提出解决方案?

推荐答案

Stack 是个好主意,但是如果您想查看完整的字符串是否用括号括起来,我建议您将Stack 上遇到的左括号的 index.这样,每次您在堆栈中弹出一个项目时,检查它是否为 0,这意味着对应于该结束括号的开始括号位于字符串的开头.最后一个结束括号的检查结果会告诉你是否需要添加括号.

The Stack is a good idea, but as you want to see if the complete string is surrounded with parens, i suggest you put the index of the encountered opening paren on the Stack. That way, each time you pop an item on the stack, check if it's 0, meaning the opening paren that corresponds to this closing paren was on the beginning of the string. The result of this check for the last closing paren will tell you if you need to add parens.

例子:

String s = "((paid for) + (8 working hours) + (company rules))";
var stack = new Stack<int>();
bool isSurroundedByParens = false;
for (int i = 0; i < s.Length; i++) {
    switch (s[i]) {
    case '(':
        stack.Push(i);
        isSurroundedByParens = false;
        break;
    case ')':
        int index = stack.Any() ? stack.Pop() : -1;
        isSurroundedByParens = (index == 0);
        break;
    default:
        isSurroundedByParens = false;
        break;
    }
}
if (!isSurroundedByParens) {
    // surround with parens
}

这篇关于如何在字符串中找到匹配的大括号对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在字符串中找到匹配的大括号对?

基础教程推荐