Codility: Brackets Determines if a given string of parentheses is set correctly.

Description of the problem from the coding:

String S, consisting of N characters, is considered correctly nested if one of the following conditions is true:

S is empty; S has the form "(U)" or "[U]" or "{U}", where U is a correctly nested string; S has the form "VW", where V and W are correctly nested strings. For example, the string "{[() ()]}" is correctly nested, but "([) ()]" is not.

Write a function:

class Solution {public int solution (String S); }

which, given the string S, consisting of N characters, returns 1 if S is correctly nested and 0 otherwise.

For example, if S = "{[() ()]}", the function should return 1 and set S = "([) ()]", the function should return 0, as explained above.

Let's pretend that:

N is an integer in the range [0,200,000]; string S consists only of the following characters: "(", "{", "[", "]", "}" and / or ")". Complexity:

expected worst-case time complexity - O (N); the expected worst spatial complexity is O (N) (not counting the storage required for the input arguments).

I get 87%. I can not understand the problem.

enter image description here

Here is my code:

   // you can also use imports, for example:
// import java.util.*;
import java.util.Stack;
// you can use System.out.println for debugging purposes, e.g.
// System.out.println("this is a debug message");

class Solution {
   public int solution(String s) {

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

        Character openingBrace = new Character('{');
        Character openingBracket = new Character('[');
        Character openingParen = new Character('(');
        Stack<Character> openingStack = new Stack<Character>();

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == openingBrace || c == openingBracket || c == openingParen) {
                openingStack.push(c);
            } else  {
                if (i == s.length()-1 && openingStack.size() != 1) {
                    return 0;
                }
                if (openingStack.isEmpty()) {
                    return 0;
                }
                Character openingCharacter = openingStack.pop();
                switch (c) {
                case '}':
                    if (!openingCharacter.equals(openingBrace)) {
                        return 0;
                    }
                    break;
                case ']':
                    if (!openingCharacter.equals(openingBracket)) {
                        return 0;
                    }
                    break;
                case ')':
                    if (!openingCharacter.equals(openingParen)) {
                        return 0;
                    }
                    break;

                default:
                    break;
                }
            } 
        }

        return 1;

    }
}
+4
source share
19 answers

, != 1. , , , . , , char /paren/..

, , (((.

, , .

+3

100/100 java.

public static int solution(String S){
    Stack<Character> stack = new Stack<Character>();
    if(null == S){
        return 0;
    }else if(S.isEmpty()){
        return 1;
    }
    for (Character C : S.toCharArray()) {

        switch (C) {
        case ')':
            pops(stack, '(');
            break;
        case '}':
            pops(stack, '{');
            break;
        case ']':
            pops(stack, '[');
            break;

        default:
            stack.push(C);
            break;
        }

    }
    return stack.isEmpty() ? 1 : 0;
}

private static void pops(Stack<Character> s, Character  C){

        while(!s.isEmpty() && s.peek() != C){
            s.pop();
        }
        if(!s.isEmpty()){
            s.pop();
        }else{
            s.push(C);
        }
}
+2

100% JavaScript

function solution(S) {
  S = S.split("");
  var stack = [];
  for (var i = 0; i < S.length; i++) {
    var c = S[i];
    if (c == '{' || c == '(' || c == '[')
      stack.push(c);
    else if (c == '}' || c == ')' || c == ']') {
      var t = stack.pop() + c;
      if (t != "{}" && t != "()" && t != "[]")
        return 0;
    }
    else 
      return 0;
  }

  if (stack.length > 0)
    return 0;

  return 1;
}
+1

# , 100% 100% . - O (N). https://codility.com/demo/results/trainingRVS3SF-DC6/

using System;
using System.Collections.Generic;

class Solution {

    public int solution(string S) {

        // Return 1 if string size is 0 
        if(S.Length==0) return 1;

        Stack<char> brackets = new Stack<char>();

        foreach(char c in S){
            if(c=='['||c=='{'||c=='('){
                brackets.Push(c);
            }
            else{
                // return 0 if no opening brackets found and 
                // first bracket is a closing bracket
                if(brackets.Count==0) return 0;

                if(c==')'){
                    if(brackets.Peek()=='(') brackets.Pop();
                    else return 0;
                }

                if(c=='}'){
                    if(brackets.Peek()=='{') brackets.Pop();
                    else return 0;
                }

                if(c==']'){
                    if(brackets.Peek()=='[') brackets.Pop();
                    else return 0;
                }
            }
        }

        if(brackets.Count==0) return 1;

        return 0;
    }
}
+1

100% java. - O (N)

 class Solution {
  public int solution(String S) {        
    char[] charArray=S.toCharArray();
    //This array works as stack
    char[] stack=new char[charArray.length];        
    //currently stack is empty
    int stackSize=0;
    for(int i=0;i<charArray.length;i++){
   //Check start characters and add it to stack
        if(charArray[i]=='{' ||charArray[i]=='(' || charArray[i]=='['){                
            stack[stackSize++]=charArray[i];                                
        }else{
            //This section checks for end character. 
           //End characters with stack being empty confirms not nested
            if(stackSize==0){
             result=0;
             break;
            }
            //Pop stack
            char ch=stack[--stackSize];   
            //check
            if((charArray[i]=='}' && ch=='{') || (charArray[i]==']' && ch=='[') ||(charArray[i]==')' && ch=='(')){                     
                continue;
            }else{
               //if pop character not matching, confirms non nesting 
                result=0;
                break;
            }                   
        }
    }
    //if stack is not empty indicates non nested, otherwise result 
    return stackSize==0?result:0;
}

}

+1

, .

O (N) O (1). 100/100 .

c++:

int solution(string  S) {
int N = S.size();
if(N == 0) return 1;//empty string is properly nested
if(S[0] == ')' || S[0] == ']' || S[0] == '}' ) return 0;// a properly nested string cannot beging with those chars
if(S[N-1] == '(' || S[N-1] == '[' || S[N-1] == '{' ) return 0; // cannot end with those chars
int paren_open = 0;
int brac_open = 0;
int curl_open = 0;
for(int i =0 ; i < N;++i){
   if(S[i] == ')' && (paren_open == 0 || S[i-1] == '[' || S[i-1] == '{')) return 0; //expected opening but got closing
   if(S[i] == ']' && (brac_open == 0 || S[i-1] == '(' || S[i-1] == '{')) return 0; //same here
   if(S[i] == '}' && (curl_open == 0 || S[i-1] == '[' || S[i-1] == '(')) return 0; //same here
   if(S[i] == '(') paren_open++;
   else if(S[i] == ')') paren_open--;
   else if(S[i] == '[') brac_open++;
   else if(S[i] == ']') brac_open--;
   else if(S[i] == '{') curl_open++;
   else if(S[i] == '}') curl_open--;
}
if(paren_open == 0 && brac_open == 0 && curl_open ==0)
   return 1;
return 0;  }
+1

Python... ! .

def solution(S):
# write your code in Python 3.6

arr = []

if len(S) < 1:
    return 1

if not isinstance(S, str):
    return 0

for i in range(0, len(S)):
    # print(S[i])
    if startSym(S[i]):
        arr.append(value(S[i]))
        # print(arr)

    elif endSym(S[i]):
        if len(arr) > 0 and value(S[i]) == arr[len(arr) - 1]:
            # print(S[i])
            # print(arr)
            del arr[len(arr) - 1]
        else:
            return 0

    else:
        return 0

if len(arr) == 0:
    return 1
else:
    return 0

def startSym(x):
if x == '{' or x == '[' or x == '(':
    return True
else:
    return False

def endSym(x):
if x == '}' or x == ']' or x == ')':
    return True
else:
    return False

def value(x):
if x == '{' or x == '}':
    return 1
if x == '[' or x == ']':
    return 2
if x == '(' or x == ')':
    return 3
+1

Python . 100%

def solution(S):

    matches, stack = dict(['()', '[]', '{}']), []

    for i in S:
        if i in matches.values():
            if stack and matches[stack[-1]] == i:
                stack.pop()
            else:
                return 0
        else:
            stack.append(i)

    return int(not stack)
+1

, (JUnit - ), , .

, Trengot , "negative_match" ))((, :

  • ))((: , , .
  • }}{{: ?
  • })({: ?
  • (}{): , , ?

, , , , ( ), .

0

, Leeor, 100% -

// you can also use imports, for example:
// import java.util.*;
import java.util.Stack;
// you can use System.out.println for debugging purposes, e.g.
// System.out.println("this is a debug message");

class Solution {
   public int solution(String s) {

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

        Character openingBrace = new Character('{');
        Character openingBracket = new Character('[');
        Character openingParen = new Character('(');
        Stack<Character> openingStack = new Stack<Character>();

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == openingBrace || c == openingBracket || c == openingParen) {
                openingStack.push(c);
            } else  {
                if (openingStack.isEmpty()) {
                    return 0;
                }
                Character openingCharacter = openingStack.pop();
                switch (c) {
                case '}':
                    if (!openingCharacter.equals(openingBrace)) {
                        return 0;
                    }
                    break;
                case ']':
                    if (!openingCharacter.equals(openingBracket)) {
                        return 0;
                    }
                    break;
                case ')':
                    if (!openingCharacter.equals(openingParen)) {
                        return 0;
                    }
                    break;

                default:
                    break;
                }
            } 
        }
        if (!openingStack.isEmpty()) {
            return 0;
        }

        return 1;

    }
}
0

: 06:12:11 UTC, c, final, score: 100.00

int solution(char *S) {
    // write your code in C99
    int len;
    if((len=strlen(S))==0) return 1;
    char stuck[len];
    char open[]="([{";
    char close[]=")]}";
    int top=0;
    for (int i=0;i<len;i++)
        {
            if (strchr(open,S[i])!=NULL)
            {
                stuck[top]=S[i];
                top++;
            } 
            else if (strchr(close,S[i])!=NULL)
            {
              if ((top>0)&&((strchr(open,stuck[top-1])-open)==(strchr(close,S[i])-close)))
              top--;
            else
                return 0;
            }
        }
        if (top==0)
        return 1;
        return 0;
    }
0

Java 100/100:

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
class Solution {
public static final int BALANCED = 1;
public static final int UNBALANCED = 0;

public int solution(String S) {
    if (S.isEmpty()) return BALANCED;

    Stack<Character> stack = new Stack<>(S.length());
    NestedValidatorUtil util = new NestedValidatorUtil();

    for (char c: S.toCharArray()) {
        if (stack.isEmpty()){
            if (util.isOpener(c)) {
                stack.push(c);
            } else {
                return UNBALANCED;
            }
        } else {
            if(util.isOpener(c)) {
                stack.push(c);
            } else if(util.getOpenerForGivenCloser(c) == stack.peek()){
                stack.pop();
            } else {
                return UNBALANCED;
            }
        }
    }

    return stack.isEmpty() ? BALANCED : UNBALANCED;
}

public static class NestedValidatorUtil {
    private Map<Character, Character> language = new HashMap<Character, Character>(){{
        put(')','(');
        put(']','[');
        put('}','{');
        }};

    public boolean isOpener(Character c) {
        return language.values().contains(c);
    }

    public Character getOpenerForGivenCloser(Character closer) {
        return language.get(closer);
    }
}

public static class Stack<T> {
      public List<T> stack;

      public Stack(int capacity) {
          stack = new ArrayList<>(capacity);
      }

      public void push(T item) {
          stack.add(item);
      }

      public T pop() {
          T item = peek();
          stack.remove(stack.size() - 1);
          return item;
      }

      public T peek() {
          int position = stack.size();
          T item = stack.get(position - 1);
          return item;
      }

      public boolean isEmpty() {
          return stack.isEmpty();
      }
  }
}

. , .

0

100% - java: https://codility.com/demo/results/training2C7U2E-XM3/

/**
 *  https://codility.com/demo/results/training2C7U2E-XM3/ 100%
 *  
 * Problem facts:
 * 1) A string S consisting of N characters is given
 * 2) S is properly nested if:
 *      -S is empty;
 *      -S has the form "(U)" or "[U]" or "{U}" where U is a properly nested string;
 *      -S has the form "VW" where V and W are properly nested strings.
 * 3) N is an integer within the range [0..200,000];
 * 4) string S consists only of the following characters: "(", "{", "[", "]", "}" and/or ")".
 * 5) expected worst-case time complexity is O(N);
 * 6) expected worst-case space complexity is O(N)
 * 
 * Solution:
 * The idea is to iterate over the string and push opening brackets, then each time a closing bracket appears
 * it will be matched with the last opening match stacked, if both are of the same type, then pop that char,
 * otherwise return 0.
 * If the string S is properly nested the remaining stack will be empty. 
 * 
 * There are three cases to analize:
 * 1) The stack is empty, push the first char.
 * 2) The stack is not empty, peek the last char and it is the opening bracket of current closing bracket, then
 * pop the char from the stack.
 * 3) The stack is not empty, peek the last char and it isn't the opening bracket of current closing bracket, 
 * return 0, because the string is malformed.
 * 
 * @param S
 * @return 1 if S is properly nested and 0 otherwise.
 */
public static int solution(String S) {      
    if(S.isEmpty()) return 1; // pay attention to corner case 1
    if(S.length()==1) return 0; // and 2

    Stack<Character> stack = new Stack<>();     

    for(int i=0; i<S.length(); i++) {
        char current = S.charAt(i);
        switch (current) {
            case '}':
                if (!stack.isEmpty() && stack.peek() == '{') {
                    stack.pop();
                } 
                else return 0;
                break;
            case ']':
                if (!stack.isEmpty() && stack.peek() == '[') {
                    stack.pop();
                } 
                else return 0;
                break;
            case ')':
                if (!stack.isEmpty() && stack.peek() == '(') {
                    stack.pop();
                } 
                else return 0;
                break;
            default:
                stack.push(current);
                break;
        }   
    }
    return stack.size()==0 ? 1 : 0;
}
0

@Moxi @Caesar Avgvstvs .

But I think mine is shorter, not missing anything. My solution passed 100% in codility . I used the card to avoid a repeat. Here is my solution in Java.

import java.util.*;

public static int solution(String S) {
    if (S.isEmpty()) return 1;
    if (S.length() % 2 == 1) return 0;  // the length cannot be an odd number.
    // in time complexity this decreases from O(n) to O(1).

    // this Map avoid the ugly "switch case"
    Map<Character, Character> map = new HashMap<Character, Character>();
    map.put('}', '{');
    map.put(')', '(');
    map.put(']', '[');

    Stack<Character> stack = new Stack<Character>();
    for (Character c : S.toCharArray()) {
        if (map.containsKey(c)) {
            if (!stack.isEmpty() && map.get(c) == stack.peek()) {
                stack.pop();
            } else {
                return 0;
            }
        } else {
            stack.push(c);
        }
    }
    return stack.isEmpty() ? 1 : 0;
}
0
source

100% Java

public int solution(String S) {
    Stack<Character> stack = new Stack<>();    
    for(int i=0; i<S.length(); i++) {
        char c = S.charAt(i);
        if (c == '[' || c == '{' || c == '(' || c == 'V') {
            stack.push(c);
        } else if (c == ']' || c == '}' || c == ')' || c == 'W') {
            if (checkBracket(stack, c)) {
                stack.pop();
            } else {
                return 0;
            }  
        } else {
            return 0;
        }
    }   
    if (stack.empty()) {
        return 1;
    }
    return 0;  
}

private boolean checkBracket(Stack<Character> stack, char bracket) {
    if (stack.empty()) return false;
    char lastStackBracket = stack.peek();
    if (lastStackBracket == '{' && bracket == '}') {
        return true;
    } else if (lastStackBracket == '[' && bracket == ']') {
        return true;
    } else if (lastStackBracket == '(' && bracket == ')') {
        return true;
    } else if (lastStackBracket == 'V' && bracket == 'W') {
        return true;
    }
    return false;
}

of course you need to import java.util:

import java.util.*;
0
source
function solution(S) {
    if (0 === S.length) {
        return 1
    }
    let stack  = []
    for (let i = 0; i < S.length; i++) {
        if ('(' === S[i] || '{' === S[i] || '[' === S[i]) {
            stack.push(S[i])
        } else {
            let couple = [stack.pop(), S[i]].join('')
            if ('()' !== couple && '{}' !== couple && '[]' !== couple) {
                return 0
            }
        } 
    }

    if (stack.length) {
        return 0
    }
    return 1
}   
0
source

My solution is in Swift. Should work correctly

public func Brackets(_ S : inout String) -> Int {

    var Stack = [Character]()

    let matching : [Character:Character] = ["(":")", "[":"]", "{":"}"]

    for s in S {
        let char = S.removeFirst()
        if "({[".contains(char) {
            print(char)
            Stack.append(char)
        }
        if( "]})".contains(char)) {
            print(char)
            let bracket = Stack.removeLast()
            if matching[bracket] != char {
                return 0
            }
        }
    }

    return 1
}

var S1 = "{[()()]}"
var S2 = "([)()]"
print("Brackets: ", Brackets(&S1))
print("Brackets: ", Brackets(&S2))
0
source

Simple Java Solution, 100/100

public int solution(String S) {
        Deque<Character> stack = new ArrayDeque<Character>();

        for(int i = 0; i < S.length(); i++) {
            char c = S.charAt(i);

            switch (c) {
                case ')':
                    if (stack.isEmpty() || stack.pop() != '(')
                        return 0;
                    break;
                case ']':
                    if (stack.isEmpty() || stack.pop() != '[')
                        return 0;
                    break;
                case '}':
                    if(stack.isEmpty() || stack.pop() != '{')
                        return 0;
                    break;
                default:
                    stack.push(c);
                    break;
            }
        }

        return stack.isEmpty() ? 1 : 0;
    }
0
source

Ruby 100%

def solution(s)
  s.split('').inject([]) do |stack, el|
    next stack.push(el) if ['[', '{', '('].include?(el)
    current = stack.pop
    next stack if (current == '{' && el == '}') ||
                  (current == '(' && el == ')') ||
                  (current == '[' && el == ']')
    return 0
  end.empty? ? 1 : 0
end
0
source

All Articles