Java Stack

It is Tuesday morning and woke up a few seconds before my alarm went off. Did some reading and decided to give Java Stack from HackerRank a try. I am quite sure I have solved this same challenge with a different name in this or a different platform. I am working on some medium level stuff and when tired will jump up to the next level.

The idea for this challenge is quite simple. One must check if the string of characters is balanced or not. In practice one would have to deal with other strings and characters embedded in the string of parenthesis to determine if the string is balanced or not.

I used the sample provided as illustrated by the following console output from the Eclipse IDE:

{}()
({()})
{}(
[]

true
true
false
true

It seems to work as expected given that the output matches the expected output.

My Java code follows:

import java.util.Scanner;
import java.util.Stack;

/*
 * 
 */
public class Solution {

	/*
	 * 
	 */
	static boolean parseInput(String input) {
	
		Stack<Character> stack = new Stack<Character>();
		char	c;
		
		// **** ****
		for (int i = 0; i < input.length(); i++) { // **** **** switch (c = input.charAt(i)) { case '{': case '(': case '[': stack.push(c); break; case '}': if (stack.isEmpty()) return false; if (!stack.pop().equals('{')) return false; break; case ')': if (stack.isEmpty()) return false; if (!stack.pop().equals('(')) return false; break; case ']': if (stack.isEmpty()) return false; if (!stack.pop().equals('[')) return false; break; } } // **** check for remaining characters in the stack **** if (!stack.isEmpty()) return false; // **** **** return true; } /* * */ public static void main(String[] args) { // **** **** Scanner sc = new Scanner(System.in); while (sc.hasNext()) { String input=sc.next(); // System.out.println("input ==>" + input + "<==");

			System.out.println(parseInput(input) ? "true" : "false");
		}
		
		// **** ****
		sc.close();
		
	}

}

I assume that there was no need to write a separate function. The code could have easily fitted inside the main() function.

If you are interested, the entire solution is also in my GitHub repository.

Keep on reading and experimenting. It is the only way to learn.

If you have comments regarding this or any other post in this blog, or if you need some help on any aspect of a software development project, please leave me a note below. Requests for project assistance will not be made public.

John

Follow me on Twitter:  @john_canessa

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.