如何找到一个字符串匹配的一对括号?(How to find the matching pair of

2019-08-17 05:49发布

假设我有一个字符串“(支付)+(工作8小时)+(公司规定)”。 现在,我要检查这个完整的字符串是否用圆括号括与否。 基本上,我想检查该字符串是这样还是没有:“((支付)+(工作8小时)+(公司规定))”。 如果已经用括号括起来,那么我会离开它,因为它是的,否则我会申请括号完整的绳子,让输出继电器是:“((支付)+(工作8小时)+(公司规定)) “。 通过计算括号中的数字,我不能够解决这个问题。

任何人都可以请提出一个解决办法?

Answer 1:

Stack是一个好主意,但你想看看完整的串用括号包围,我建议你把上遇到的开括号的索引 Stack 。 这样一来,每次在栈上弹出一个项目的时候,检查它是否是0 ,这意味着相当于今天的闭幕括号是在字符串的开头开括号。 如果您需要添加括号这支票最后收括号的结果会告诉你。

例:

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
}


Answer 2:

使用堆栈..在当u找到(支架推它,当你看到)弹出堆栈。最后当字符串被解析完全堆栈应该是空的......这将确保你的括号不缺..

你的情况,如果在的堆栈变为空,然后有针对整个字符串周围没有括号

例如:对于输入字符串:

(支付)+(工作8小时)+(公司规定)

第一个(将被推动,当它遇到的),它会弹出堆栈,现在检查是否有被解析更字符串,堆栈不为空。 如果栈是空的,这意味着整个字符串不是支架。

而对于字符串:

((支付)+(工作8小时)+(公司规定))

直到最后一个)出现堆栈不会是空的。

希望这可以帮助...



Answer 3:

测试

static void Main()
{
    Console.WriteLine("Expected: {0}, Is: {1}", false, IsSurrounded(""));
    Console.WriteLine("Expected: {0}, Is: {1}", false, IsSurrounded("("));
    Console.WriteLine("Expected: {0}, Is: {1}", false, IsSurrounded(")"));
    Console.WriteLine("Expected: {0}, Is: {1}", true, IsSurrounded("()"));
    Console.WriteLine("Expected: {0}, Is: {1}", false, IsSurrounded("(()"));
    Console.WriteLine("Expected: {0}, Is: {1}", false, IsSurrounded("())"));
    Console.WriteLine("Expected: {0}, Is: {1}", true, IsSurrounded("(.(..)..(..)..)"));
    Console.WriteLine("Expected: {0}, Is: {1}", false, IsSurrounded("(..)..(..)"));
    Console.WriteLine("Expected: {0}, Is: {1}", false, IsSurrounded("(..)..(..)..)"));
    Console.WriteLine("Expected: {0}, Is: {1}", false, IsSurrounded("(.(..)..(..)"));
}

方法

非常快

  • 没有堆栈
  • 通过整个字符串没有循环

如果第一个开括号有其对应的结束,那么结果不可能是真实的。 关于最后一个右括号同样的事情。

static bool IsSurrounded(string text)
{
    if (text.Length < 2 || text.First() != '(' || text.Last() != ')')
        return false;

    for (var i = 1; i < text.Length - 1; i++)
    {
        if (text[i] == ')')
            return false;

        if (text[i] == '(')
            break;
    }

    for (var i = text.Length - 2; i > 0; i--)
    {
        if (text[i] == '(')
            return false;

        if (text[i] == ')')
            break;
    }

    return true;
}

限制

应当有更多的递归的括号如可以不使用((..)) + ((..))



Answer 4:

为了确保有括号,你可以简单地添加它们:

text = "(" + text + ")"

否则,建议通过堆栈Botz3000:

string text = "(paid for)";

Stack<int> parenthesis = new Stack<int>();
int last = 0;

for (int i = 0; i < text.Length; i++)
{
    if (text[i] == '(')
        parenthesis.Push(i);
    else if (text[i] == ')')
    {
        last = parenthesis.Pop();
    }
}

if (last == 0)
{
    // The matching parenthesis was the first letter.
}


Answer 5:

您可以通过使用像堆栈检查parenthesises权数。 上数各开倒计时每个右大括号。 相同数量的开闭括号的意味着它相匹配。 如果你遇到一个右括号,而你的计数为零,这是一个不匹配。 如果你想知道,如果你的字符串完全被封闭paranthesises,检查是否所有的人匹配,那么请检查您的字符串以一个开始。

static void BraceMatch(string text)
{
  int level = 0;

  foreach (char c in text)
  {
    if (c == '(')
    {
      // opening brace detected
      level++;
    }

    if (c == ')')
    {
      level--;

      if (level < 0)
      {
        // closing brace detected, without a corresponding opening brace
        throw new ApplicationException("Opening brace missing.");
      }
    }
  }

  if (level > 0)
  {
    // more open than closing braces
    throw new ApplicationException("Closing brace missing.");
  }
}


Answer 6:

发现右括号索引

public int FindClosingBracketIndex(string text, char openedBracket = '{', char closedBracket = '}')
{
            int index = text.IndexOf(openedBracket);
            int bracketCount = 1;
            var textArray = text.ToCharArray();

            for (int i = index + 1; i < textArray.Length; i++)
            {
                if (textArray[i] == openedBracket)
                {
                    bracketCount++;
                }
                else if (textArray[i] == closedBracket)
                {
                    bracketCount--;
                }

                if (bracketCount == 0)
                {
                    index = i;
                    break;
                }
            }

            return index;
}


文章来源: How to find the matching pair of braces in a string?
标签: c# string stack