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

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

问题描述

假设我有一个字符串 "(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.

任何人都可以提出解决方案吗?

Can anyone please suggest a solution?

推荐答案

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
}

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆