Saturday, May 2, 2015

Stacks and Queues - Nesting

Here is another codility problem solution from the codility lessons (Nesting -Determine whether given string of parentheses is properly nested.) due to the copy rights I can't copy the content of the problem here so to view the problem description click here.




// you can also use imports, for example:
import java.util.*;

// 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) {
		// write your code in Java SE 8
		if (S.length() % 2 != 0) return 0;
		if (S.length() == 0) return 1;



		Stack < Character > st = new Stack < Character > ();
		for (int i = 0; i < S.length(); i++) {

			if (isOpenTag(S.charAt(i))) {
				st.add(S.charAt(i));
			} else {
				if (!st.empty()) {
					char sc = st.pop();
					if (getCloseTag(sc) != S.charAt(i)) return 0;
				} else {
					return 0;
				}
			}

		}
		if (!st.empty()) return 0;

		return 1;


	}

	private char getCloseTag(char c) {
		switch (c) {
			case ('('):
				return ')';
			default:
				return ' ';

		}
	}

	private boolean isOpenTag(char c) {
		switch (c) {
			case ('('):
				return true;


			default:
				return false;

		}
	}

}

No comments:

Post a Comment