Nesting

Determine whether a given string of parentheses (single type) is properly nested.


Solution:

Solution to Codility's Nesting problem which is from the Codility Lesson 7: Stacks and Queues and, is solved in Java 8 with 100% performance and correctness scores. The goal here is to determine whether a given string of parentheses (single type) is properly nested. You can find the question of this Nesting problem in the Codility website.


package Codility.Lesson7;

import java.util.*;

public class Nesting {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String in2 = "fsds fsdf( sdfsd ) dfsdf sd(dsfsd)fsdfsdf sdf(fsdfsd(sfsd f)fsdf(sfsdf fds)";
		//String in2 = "([)()]";
		int result = solution(in2);
		System.out.println(result);
	}

    public static int solution(String S) {
        // write your code in Java SE 8
        Stack <Character> stack = new Stack<Character>();

       for(int i=0; i<S.length(); i++){
           char c = S.charAt(i);
           if (c == '('){
               stack.push(c);
           }else if(c ==')'){
               if(stack.size() ==0) {    
                   return 0;
               }else {
            	   stack.pop();
               }
           }
       }
       if(stack.size()==0){
       return 1;
       }else{
           return 0;
       }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *