检查Dart中仅包含括号的字符串中的括号是否对称

0mkxixxg  于 2022-12-06  发布在  其他
关注(0)|答案(5)|浏览(127)

给定只包含字符(){}[]的字符串s,确定输入字符串是否有效。
如果满足以下条件,则输入字符串有效:

  • 左括号必须由相同类型的括号关闭。
  • 左括号必须以正确的顺序关闭。

例一:

  • 输入:s = "()",输出:真的

例二:

  • 输入:s = "()[]{}",输出:真的

例三:

  • 输入:s = "(]",输出:假的
vxbzzdmp

vxbzzdmp1#

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

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
}
nfeuvbwi

nfeuvbwi2#

下面是dart中两种不同的解决方案:

main() {
  print(isValid("()[]{}")); // true
  print(isValid("()[){}")); // false
  print(isValid("{{)){")); // false
  print(isValid("(){}()")); // true
  print(isValid("[][]()")); // true
  print(isValid("{{()([][{{{}}")); // false
  print(isValid("{(({[[{([[[]]])}]]}))}")); // true
  print("\n");
  print("Soltion 2");
  print(isValidSolution2("()[]{}")); // true
  print(isValidSolution2("()[){}")); // false
  print(isValidSolution2("{{)){")); // false
  print(isValidSolution2("(){}()")); // true
  print(isValidSolution2("[][]()")); // true
  print(isValidSolution2("{{()([][{{{}}")); // false
  print(isValidSolution2("{(({[[{([[[]]])}]]}))}")); // true
}

bool isValid(String s) {
  List invalid_combo_strings = ["{]", "{)", "[}", "[)", "(}", "(]"];
  List invalid_start_strings = ["}", "]", ")"];
  List invalid_end_strings = ["{", "[", "("];

  if (s.length % 2 != 0) {
    return false;
  }

  if (invalid_start_strings.contains(s[0]) ||
      invalid_end_strings.contains(s[s.length - 1])) {
    return false;
  }

  return !invalid_combo_strings.any((v) => s.contains(v));
}

// solution2
isValidSolution2(String s) {
  List openBrackets = ["{", "(", "["];
  List closeBrackets = ["}", ")", "]"];
  List validatorList = [];

  if (s.isEmpty) {
    return true;
  }

  for (String c in s.split('')) {
    // add the first character if validator
    // list is
    // empty
    if (validatorList.isNotEmpty && closeBrackets.contains(c)) {
      if (openBrackets[closeBrackets.indexOf(c)] != validatorList.last) {
        // at most one falsy condition defaulted it
        return false;
      } else {
        validatorList.removeLast();
      }
    } else {
      validatorList.add(c);
    }
  }
  // print(validatorList);
  return validatorList.isEmpty;
}
vuktfyat

vuktfyat3#

我想这会对你有帮助

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;
}
vohkndzv

vohkndzv4#

您可以检查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('({()}{[}])'))
r8xiu3jd

r8xiu3jd5#

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;
  }
}

相关问题