Created
April 10, 2017 21:56
-
-
Save Lodo4ka/426012375bb66258be14b5cfc18b6c5e to your computer and use it in GitHub Desktop.
From https://www.hackerrank.com/challenges/java-stack/forum Input Format There will be multiple lines in the input file, each having a single non-empty string. You should read input till end-of-file. The part of the code that handles input operation is already provided in the editor. Output Format For each case, print 'true' if the string is bal…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
class Solution{ | |
private static Map<String,String> myMap = createMap(); | |
private static Map<String,String> createMap() { | |
HashMap<String,String> result = new HashMap<String,String>(); | |
result.put("(",")"); | |
result.put("[","]"); | |
result.put("{","}"); | |
return Collections.unmodifiableMap(result); | |
} | |
public static void main(String []argh) | |
{ | |
Scanner sc = new Scanner(System.in); | |
while (sc.hasNext()) { | |
String input=sc.nextLine(); | |
Stack myStack = new Stack(); | |
String last; | |
String next; | |
for (int i=0 ; i<input.length(); i++){ | |
next = Character.toString(input.charAt(i)); | |
if (myStack.empty()) { | |
myStack.push(next); | |
} else { | |
last = myStack.peek().toString(); | |
if (myMap.containsKey(last)) { | |
if (myMap.get(last).equals(next)){ | |
myStack.pop(); | |
} else { | |
myStack.push(next); | |
} | |
} else { | |
myStack.push(next); | |
break; | |
} | |
} | |
} | |
System.out.println(myStack.empty()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment