Showing posts with label Stacks and Queues. Show all posts
Showing posts with label Stacks and Queues. Show all posts

Saturday, May 2, 2015

Stacks and Queues - Fish

Here is another codility problem solution from the codility lessons (Fish-N voracious fish are moving along a river. Calculate how many fish are alive.) 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(int[] A, int[] B) {

		int count = 0;
		Stack < Integer > previousFishes = new Stack < Integer > ();

		for (int i = 0; i < A.length; i++) {
			int currentFish = A[i];
			int currentFlow = B[i];
			if (currentFlow == 1) {
				previousFishes.push(currentFish);
			}
			if (!previousFishes.empty() && currentFlow == 0) {
				while (!previousFishes.empty() && currentFish > previousFishes.peek()) {
					int fish = previousFishes.pop();
				}
			}
			if (previousFishes.empty() && currentFlow == 0) {
				count++;
			}

		}
		return count + previousFishes.size();
	}
}

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;

		}
	}

}