C#如何找到多余的)或(字符串中的括号,然后将其替换为@

时间:2019-03-01 12:15:47

标签: c#

C#如何在字符串中找到多余的)(括号,并将其替换为@

样本输入

)(more)))
((((more)))
((((more))
(about)((index)(more)))
(about)((index)(more)())
(about)(((index)(more)
(about)(((index)(more
(about)(((index)(more)))))

样本输出

@(more)@@
@(((more)))
@@((more))
(about)((index)(more))@
(about)((index)(more)())
(about)@@(index)(more)
(about)@@(index)@more
(about)(((index)(more)))@@

1 个答案:

答案 0 :(得分:4)

在一个经典问题上有一些妙处。与任何括号匹配问题一样,我们需要保留一堆不匹配的右括号,并在找到对应的右括号时清除它们。

对问题中的示例进行很好的工作-它们对于确定确切的行为非常有帮助。

public static string BalanceBrackets(string input)
{
    // First, we'll do a straight pass through the string. Every time we find a '(', we'll
    // record it in a stack. Every time we find a ')', we'll check whether there's a
    // corresponding '(' in the stack: if there is, we'll pop it; if there isn't, we've
    // got an unmatched ')' and we'll replace it with a '@'.
    // When we're done, any unmatched '('s will be in the stack. Replace each of these with
    // a '@'.

    char[] chars = input.ToCharArray();

    // Positions of all unmatched open parens
    var unmatchedOpens = new Stack<int>();

    for (int i = 0; i < chars.Length; i++)
    {
        if (chars[i] == '(')
        {
            unmatchedOpens.Push(i);
        }
        else if (chars[i] == ')')
        {
            if (unmatchedOpens.Count > 0)
            {
                unmatchedOpens.Pop();   
            }
            else
            {
                chars[i] = '@'; 
            }
        }
    }

    while (unmatchedOpens.Count > 0)
    {
        int pos = unmatchedOpens.Pop();
        chars[pos] = '@';
    }

    return new string(chars);
}

See it in action