【问题标题】:Check if brackets are balanced in a string containing only brackets in Dart给定一个仅包含字符 \'(\', \')\', \'{\', \'}\', \'[\' 和 \']\' 的字符串 s,确定输入字符串是否为在 Dart 中有效
【发布时间】:2022-08-16 06:18:07
【问题描述】:

给定一个仅包含字符 \'(\', \')\', \'{\', \'}\', \'[\' 和 \']\' 的字符串 s,确定输入字符串是否为有效的。

输入字符串在以下情况下有效:

开括号必须用相同类型的括号闭合。 开括号必须以正确的顺序闭合。

示例 1:

输入:s = \"()\" 输出:真 示例 2:

输入:s = \"()[]{}\" 输出:真 示例 3:

输入:s = \"(]\" 输出:假

  • 我投票结束这个问题,因为 OP 有一种模式,即发布看起来陈规定型的面试问题,而不代表它们,并且目标是自我回答(很糟糕)。他们似乎不是真诚地提出问题,OP真正想要答案,任何回答都可能是在浪费时间。
  • 我确实写了这个问题的答案,但出于上述原因,我将其撤回。

标签: dart


【解决方案1】:

**我认为它会帮助你:**

void main() {
  print(isValid("()[]{}(([[[]]]))"));
}

isValid(String str) {
  var isValidSymbol = true;
  var tmpStr = "";
  
  if(str.length % 2 != 0) {
    return false;
  }
  
   for(int i = 0; i < str.length; i++) {
     var tmpChr = str[i];
     if(tmpChr == "(" || tmpChr == "{" || tmpChr == "[") {
       tmpStr += tmpChr;
     } else {
         if(tmpChr == ")" && tmpStr[tmpStr.length - 1] != "(") {
             isValidSymbol = false;
         } else if(tmpChr == "}" && tmpStr[tmpStr.length - 1] != "{") {
             isValidSymbol = false;
         } else if(tmpChr == "]" && tmpStr[tmpStr.length - 1] != "[" ) {
             isValidSymbol = false;
         } else {
             tmpStr = tmpStr.substring(0, tmpStr.length - 1);
         }
      }
   }
    
  return isValidSymbol;
}

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:

您可以查看this,但它是用 python 编写的

# Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', 
# determine if the input string is valid.
# An input string is valid if: Open brackets must be closed by the same type of brackets. 
# Open brackets must be closed in the correct order.

import re

def isValid(s: str) -> bool:
    if (s == ''):
        return True
    elif not ((s.count('(') - s.count(')')) == 0 and (s.count('[') - s.count(']')) == 0 and (s.count('{') - s.count('}')) == 0):
        return False
    else:
        _result = [re.search(pattern, s)
                   for pattern in ['\((.)*\)', '\[(.)*\]', '\{(.)*\}']]
        _result = ['' if _result[i] is None else _result[i].group()[1:-1]
                   for i in range(len(_result))]
        return isValid(_result[0]) and isValid(_result[1]) and isValid(_result[2])


if __name__ == '__main__':
    print(isValid('([]){'))
    print(isValid('[]'))
    print(isValid('(]'))
    print(isValid('([)]'))
    print(isValid('{[]}'))
    print(isValid('({()}{[}])'))

【讨论】:

    【解决方案3】:

    不是最简短的答案,而是可读的:

    void main() {
      isValid(String s) {
        var type1 = true;
        var type2 = true;
        var type3 = true;
        var array = [];
    
        for (var char in s.split('')) {
          switch (char) {
            case '(':
              type1 = false;
              array.add('type1');
              break;
            case ')':
              type1 = array.isEmpty ? false : array.removeLast() == 'type1';
              break;
            case '[':
              type2 = false;
              array.add('type2');
              break;
            case ']':
              type2 = array.isEmpty ? false : array.removeLast() == 'type2';
              break;
            case '{':
              type3 = false;
              array.add('type3');
              break;
            case '}':
              type3 = array.isEmpty ? false : array.removeLast() == 'type3';
              break;
            default:
              break;
          }
        }
        return type1 && type2 && type3;
      };
    
      print(isValid('()[]{}')); //true
      print(isValid('([])')); //true
      print(isValid('([])]')); //false
      print(isValid('([)]')); //false
    }
    

    【讨论】:

      【解决方案4】:
      void main() {
      //   Input: s = "()"
      // Output: true
      
      // Input: s = "()[]{}"
      // Output: true
      
        bool check = validParantheses('()[]{}{}]{');
        print(check);
      }
      
      bool validParantheses(String paran) {
        if (paran.length % 2 != 0) {
          return false;
        } else {
          for (var i = 0; i < paran.length; i += 2) {
            var firstChar = paran[i];
            var secondChar = paran[i + 1];
      
            var closingChar = returnClosingParan(firstChar);
      
            if (closingChar != secondChar) {
              return false;
            }
          }
          return true;
        }
      }
      
      returnClosingParan(paran) {
        switch (paran) {
          case '(':
            return ")";
          case '[':
            return "]";
          case '{':
            return "}";
          default:
            return;
        }
      }
      

      【讨论】:

      • 这不适用于'(())' 之类的输入。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-18
      • 1970-01-01
      • 2014-01-29
      • 2019-06-11
      • 2011-02-24
      • 1970-01-01
      • 2014-01-14
      相关资源
      最近更新 更多