Valid braces
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.
export function validBraces(braces: string): boolean {
while(/\(\)|\[\]|\{\}/g.test(braces)){
braces = braces.replace(/\(\)|\[\]|\{\}/g,"")
}
return !braces.length;
}
import re
def valid_braces(braces: str) -> bool:
while re.search(r"\(\)|\[\]|\{\}", braces):
braces = re.sub(r"\(\)|\[\]|\{\}", "", braces)
return len(braces) == 0
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
}
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
}
#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();
}
function validBraces($braces) {
while (preg_match('/\(\)|\[\]|\{\}/', $braces)) {
$braces = preg_replace('/\(\)|\[\]|\{\}/', '', $braces);
}
return empty($braces);
}
Go to Kata
Want us to give you some help with your business? No problem, here's a video on who we can help, and how, along with our calendar so you can book in a call to discuss us working together.
Let's see