gpt4 book ai didi

C#如何在字符串中找到多余的 ) 或 ( 括号,并用@替换它们

转载 作者:太空宇宙 更新时间:2023-11-03 20:51:18 25 4
gpt4 key购买 nike

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)))@@

最佳答案

经典问题的巧妙转折。与任何括号匹配问题一样,我们需要保留一堆不匹配的左括号,并在找到相应的右括号时清除它们。

问题中的示例做得很好 - 它们对于弄清楚确切的行为应该是什么非常有帮助。

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

关于C#如何在字符串中找到多余的 ) 或 ( 括号,并用@替换它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54944493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com