Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 平衡大括号的程序_C#_Arrays_String_If Statement_Conditional - Fatal编程技术网

C# 平衡大括号的程序

C# 平衡大括号的程序,c#,arrays,string,if-statement,conditional,C#,Arrays,String,If Statement,Conditional,您好,我有一个字符串数组,其中包含值为“{[()]}”、“}[]{”、“{()[]”。现在我必须平衡大括号,就像每个起始大括号一样,例如,{或[或(,必须有一个右大括号。如果输入字符串的开始大括号和结束大括号的数量相同,则输出为“是”,否则为“否”。此外,如果字符串在匹配的开始大括号之前有一个结束大括号,则输出也将是“否”。因此,基本上,输出必须是一个字符串数组,其中包含上述输入字符串数组的值:“是”、“否”、“否” 我编写了下面的程序,其中有很多if-else条件。我想知道在C#中是否有更好的

您好,我有一个字符串数组,其中包含值为“{[()]}”、“}[]{”、“{()[]”。现在我必须平衡大括号,就像每个起始大括号一样,例如,{或[或(,必须有一个右大括号。如果输入字符串的开始大括号和结束大括号的数量相同,则输出为“是”,否则为“否”。此外,如果字符串在匹配的开始大括号之前有一个结束大括号,则输出也将是“否”。因此,基本上,输出必须是一个字符串数组,其中包含上述输入字符串数组的值:“是”、“否”、“否”

我编写了下面的程序,其中有很多if-else条件。我想知道在C#中是否有更好的方法来处理这个问题

static void Main(string[] args)
{
  string[] arrBraces = Console.ReadLine().Split(' ');
  string[] result = new String[arrBraces.Length];

  for (int i = 0; i < arrBraces.Length; i++) {
    Console.WriteLine(arrBraces[i]);
    int curly = 0, square = 0, round = 0;

    foreach (char c in arrBraces[i]) {
      if (c == '{') {
        curly++;
      } else if (c == '[') {
        square++;
      } else if (c == '(') {
        round++;
      } else if (c == '}') {
        if (curly > 0) {
          curly--;
        } else {
          curly = -1;
          break;
        }
      } else if (c == ']') {
        if (square > 0) {
          square--;
        } else {
          square = -1;
          break;
        }
      } else if (c == ')') {
        if (round > 0) {
          round--;
        } else {
          round = -1;
          break;
        } 
      }
    }

    if (curly == 0 && square == 0 && round == 0) {
      result[i] = "YES";
    } else {
      result[i] = "NO";
    }
  }

  foreach (string str in result) {
    Console.WriteLine (str);
  }
  Console.ReadKey();
}
static void Main(字符串[]args)
{
字符串[]arrbrases=Console.ReadLine().Split(“”);
字符串[]结果=新字符串[arrblaces.Length];
for(int i=0;i0){
卷曲--;
}否则{
卷曲=-1;
打破
}
}else如果(c==']'){
如果(平方>0){
正方形--;
}否则{
平方=-1;
打破
}
}如果(c=='),则为else){
如果(四舍五入>0){
圆--;
}否则{
轮数=-1;
打破
} 
}
}
如果(卷曲==0&&square==0&&round==0){
结果[i]=“是”;
}否则{
结果[i]=“否”;
}
}
foreach(结果中的字符串str){
Console.WriteLine(str);
}
Console.ReadKey();
}
我发现了一个类似的问题,但它似乎也在做同样的事情,只是它使用堆栈来存储括号,而我的问题明确指出大括号位于字符串数组中


无论如何,如果您能提供任何帮助或建议来改进代码,我们将不胜感激。

您当然可以将其变得更加简洁:

public static bool CheckString(string input)
{
    int braceSum = 0, squareSum = 0, parenSum = 0;

    foreach(char c in input)
    {   //adjust sums
        if (c == '{') braceSum++;
        if (c == '}') braceSum--;
        if (c == '[') squareSum++;
        if (c == ']') squareSum--;
        if (c == '(') parenSum++;
        if (c == ')') parenSum--;

        //check for negatives (pair closes before it opens)
        if (braceSum < 0 || squareSum < 0 || parenSum < 0) return false;
    }
    return (braceSum == 0 && squareSum == 0 && parenSum == 0);
}
问题中有一点尚不清楚,那就是这是否合法:

({)}

根据示例代码,这是合法的,因为这看起来像是一个实践练习,可能并不重要。但是,对于本练习描述的现实世界问题,这通常(不总是,但经常)是不合法的,并且被认为是“不平衡的”。如果这很重要,您需要使用单个
堆栈
而不是单个求和,您的
CheckString()
方法可能如下所示:

public static bool CheckString(string input)
{   //Use the closer rather than opener as the key.
    // This will give better lookups when we pop the stack
    var pairs = new Dictionary<char, char>() {
        { '}','{' },  { ']','[' },   { ')','(' }
    }
    var history = new Stack<char>();

    foreach(char c in input)
    {
        if (pairs.ContainsValue(c)) history.Push(c);
        if (pairs.ContainsKey(c) && (history.Count == 0 || history.Pop() != pairs[c]))
            return false;
    }
    return (history.Count == 0);
}
publicstaticboolcheckstring(字符串输入)
{//使用闭合器而不是打开器作为键。
//当我们弹出堆栈时,这将提供更好的查找
var pairs=新字典(){
{ '}','{' },  { ']','[' },   { ')','(' }
}
var history=新堆栈();
foreach(输入中的字符c)
{
if(pairs.ContainsValue(c))history.Push(c);
if(pairs.ContainsKey(c)&&(history.Count==0 | | | history.Pop()!=pairs[c]))
返回false;
}
返回(history.Count==0);
}
遵循以下算法:

1) 使用堆栈

2) 从左边读取字符串

3) 如果当前读取的字母是大括号(“(”、“{”、“[”),则推送到堆栈

4) 如果当前已读字母为右大括号,则从堆栈中弹出

5) 用当前读取的大括号检查弹出的大括号

5.a)如果是配对大括号。确定是否继续

5.b)如果堆栈为空,则打印“否”

5.c)如果弹出字符和读取字符不是一对,则打印否

6) 处理完所有字符串后,请检查堆栈的长度

6.a)如果长度为0,则打印“是”

6.b)其他打印编号

公共静态布尔值有效位(大括号)
        public static bool ValidBraces(String braces)
        {
            if (String.IsNullOrWhiteSpace(braces))
            {
                //invalid
                return false;
            }

            Stack<char> stack = new Stack<char>();

            for (int i = 0; i < braces.Length; i++)
            {
                //if its an open brace, stack
                if (braces[i] == '{' || braces[i] == '[' || braces[i] == '(')
                {
                    stack.Push(braces[i]);
                }
                else if (stack.Count != 0)
                {
                    //if its a closed brace, compare with the complement and pop from stack
                    if (stack.Pop() != complement(braces[i]))
                    {
                        //invalid
                        return false;
                    }
                }
                else
                {
                    //invalid, missing brace
                    return false;
                }
            }

            if (stack.Count != 0)
            {
                //invalid, there are still some braces without match
                return false;
            }

            //valid, success
            return true;
        }

        private static char complement(char item)
        {
            switch (item)
            {
                case ')':
                    return '(';
                case '}':
                    return '{';
                case ']':
                    return '[';
                default:
                    return ' ';
            }
        }

        //this is for test. Put it on some method.
        System.Console.WriteLine("" + ValidBraces(""));//false
        System.Console.WriteLine("()" + ValidBraces("()"));//true
        System.Console.WriteLine("[(])" + ValidBraces("[(])"));//false
        System.Console.WriteLine("[()]{}" + ValidBraces("[()]{}"));//true
        System.Console.WriteLine("[({)]}" + ValidBraces("[({)]}"));//false
        System.Console.WriteLine("[[()]{}" + ValidBraces("[[()]{}"));//false
{ if(String.IsNullOrWhiteSpace(大括号)) { //无效的 返回false; } 堆栈=新堆栈(); for(int i=0;i
在任何情况下,平衡大小写中的内部项应为()、{}或[]

Usage  
...........................
string text = "()[][][((()))]{}";
bool isBalanced = IsBalanced(text);
...........................

Method
...........................
bool IsBalanced(string s)
{
int textCount = 0;

do
{
s = s.Replace("[]", string.Empty).Replace("{}", string.Empty).Replace("()", string.Empty);
if (textCount==s.Length)
{
return false;
}
else
{
textCount = s.Length;
}

} while (s.Length>0);

return true;
}

我将使用队列和堆栈
Usage  
...........................
string text = "()[][][((()))]{}";
bool isBalanced = IsBalanced(text);
...........................

Method
...........................
bool IsBalanced(string s)
{
int textCount = 0;

do
{
s = s.Replace("[]", string.Empty).Replace("{}", string.Empty).Replace("()", string.Empty);
if (textCount==s.Length)
{
return false;
}
else
{
textCount = s.Length;
}

} while (s.Length>0);

return true;
}
        var dictionary = new Dictionary<string, string>() {
            { "{", "}" },
            {"[", "]" },
            {"(",")" }
        };


        var par = "{()}";
        var queue = new Queue();
        var stack = new Stack();

        bool isBalanced = true;

        var size = par.ToCharArray().Length;

        if(size % 2 != 0)
        {
            isBalanced = false;
        }
        else
        {
            foreach (var c in par.ToCharArray())
            {
                stack.Push(c.ToString());
                queue.Enqueue(c.ToString());
            }

            while (stack.Count > size/2 && queue.Count > size/2)
            {
                var a = (string)queue.Dequeue();
                var b = (string)stack.Pop();

                if (dictionary.ContainsKey(a) && b != dictionary[a])
                {
                    isBalanced = false;

                }


            }


        }

        Console.WriteLine(isBalanced?"balanced!":"Not Balanced");

        Console.ReadLine();
  public boolean isValid(String input) {

    Map<Character, Character> map = new HashMap<>();
        map.put('<', '>');
        map.put('{', '}');
        map.put('[', ']');
        map.put('(', ')');

     Stack<Character> stack = new Stack<>();

     for(char ch : input.toCharArray()){
         if(map.containsKey(ch)){
             stack.push(ch);
         } else if(!stack.empty() && map.get(stack.peek())==ch){
             stack.pop();
         } else {
             return false;
         }
     }
     return stack.empty();
 }
public static Boolean isBalanced(String input){

  return Regex.Replace(input, @"[^\[\]\{\}()]", "").Replace("[]", "").Replace("{}","").Replace("()","").Length > 0 ? false : true;

}