我想检查输入字符串是否包含相同数量的开/关括号。如果是,则打印出 true 否则为 false。我已经写了这段代码但是有一些错误有人可以帮忙吗?
See My Code 如果我输入一个以左括号开头并以右括号结尾的字符串“()”,这就可以正常工作,但是如果我输入“)(”,那么它仍然会打印出 true?。输出应该是:
() = true
(())=true
()) = false
(() = false
)( = false
)(() = false
etc...
感谢帮助
编辑:
using System;
public class Program
{
public void Main()
{
CheckParentheses ("()");
}
public void CheckParentheses (string inputParentheses){
int openParentheses = 0;
int closeParentheses = 0;
for (int i = 0; i < inputParentheses.Length; i++)
{
if (inputParentheses[i] == '(')
{
openParentheses++;
}
if (inputParentheses[i] == ')') {
closeParentheses++;
}
if (openParentheses == closeParentheses)
Console.WriteLine("true");
}
}
}
最佳答案
您可以检查他们的顺序,而不是计算开/关括号
public void CheckParentheses(string inputParentheses)
{
// Level counter
int parenLevel = 0;
for (int i = 0; i < inputParentheses.Length; i++)
{
// Open always good, increment the level
if (inputParentheses[i] == '(')
parenLevel++;
else if (inputParentheses[i] == ')')
parenLevel--;
// Closing good, but only if the level doesn't drop under zero
if (parenLevel < 0)
{
Console.WriteLine("false");
return;
}
}
// At the end of the loop, the level should always be zero
if(parenLevel != 0)
Console.WriteLine("false");
else
Console.WriteLine("true");
}
关于c# - 如何检查括号是否相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35259799/