Kata of the Day #6

Valid braces

kata
kata
kata
kata
kata
kata
kata
kata
kata
kata
kata
kata
kata
kata
kata
kata
kata
kata
kata
kata
Kata of the Day #6

Write a function that takes a string of braces, and determines if the order of the braces is valid. It should return true if the string is valid, and false if it's invalid.

This Kata is similar to the Valid Parentheses Kata, but introduces new characters: brackets [], and curly braces {}. Thanks to @arnedag for the idea!

All input strings will be nonempty, and will only consist of parentheses, brackets and curly braces: ()[]{}. What is considered Valid?

A string of braces is considered valid if all braces are matched with the correct brace.

TypeScript


export function validBraces(braces: string): boolean {
  while(/\(\)|\[\]|\{\}/g.test(braces)){
    braces = braces.replace(/\(\)|\[\]|\{\}/g,"")
  }
  return !braces.length;
}

Python


import re

def valid_braces(braces: str) -> bool:
    while re.search(r"\(\)|\[\]|\{\}", braces):
        braces = re.sub(r"\(\)|\[\]|\{\}", "", braces)
    return len(braces) == 0

Go


package kata

import "regexp"

func ValidBraces(braces string) bool {
  for {
    re := regexp.MustCompile(`\(\)|\[\]|\{\}`)
    if !re.MatchString(braces) {
      break
    }
    braces = re.ReplaceAllString(braces, "")
  }
  return len(braces) == 0
}

Rust


use regex::Regex;

fn valid_braces(braces: &str) -> bool {
    let mut s = String::from(braces);
    let re = Regex::new(r"\(\)|\[\]|\{\}").unwrap();
    
    while re.is_match(&s) {
        s = re.replace_all(&s, "").to_string();
    }
    
    s.len() == 0
}

C++


#include 
#include 
#include 

bool valid_braces(std::string braces) {
    std::regex re("\\(\\)|\\[\\]|\\{\\}");
    while (std::regex_search(braces, re)) {
        braces = std::regex_replace(braces, re, "");
    }
    return braces.empty();
}

PHP


function validBraces($braces) {
  while (preg_match('/\(\)|\[\]|\{\}/', $braces)) {
    $braces = preg_replace('/\(\)|\[\]|\{\}/', '', $braces);
  }
  return empty($braces);
}

Go to Kata

Share

Need a budget?

Let's talk
budget
budget
budget
budget
budget
budget
budget
budget
budget
budget