# Bracket Matcher Coderbyte Solution

0

Title: Bracket Matcher

Difficulty: Medium

Maximum Score: 10

Description: For this challenge, you will determine if the brackets in a string are correctly matched up.

Have the function BracketMatcher(str) take the str parameter being passed and return 1 if the brackets are correctly matched and each one is accounted for. Otherwise return 0. For example: if str is "(hello (world))", then the output should be 1, but if str is "((hello (world))" the the output should be 0 because the brackets do not correctly match up. Only "(" and ")" will be used as brackets. If str contains no brackets return 1.

Java

import java.util.*;
import java.io.*;

class Main {

public static String BracketMatcher(String str) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < str.length(); i++){
char c = str.charAt(i);
if (c == '(' ) stack.push(c);
else if (c == ')' ) {
if (stack.isEmpty()) return "0";
else stack.pop();
}
}
return "" + (stack.isEmpty()? 1:0);
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(BracketMatcher(s.nextLine()));
}
}

C

#include <stdio.h> #include <string.h> void BracketMatcher(char *str) { // code goes here int br = 0; for (int i = 0; i < strlen(str); i++) { if (str[i] == '(') { br++; } else if (str[i] == ')') { br--; if (br < 0)break; } } if (br != 0)printf ("0"); else printf("1"); } int main(void) { // keep this function call here BracketMatcher(coderbyteInternalStdinFunction(stdin)); return 0; }