You are viewing a single comment's thread. Return to all comments →
import java.util.*; class Solution{ public static boolean check(String s) { Stack stack = new Stack<>(); for (char ch : s.toCharArray()) { if (ch == '(' || ch == '{' || ch == '[') { stack.push(ch); } else if (ch == ')' || ch == '}' || ch == ']') { if (stack.isEmpty()) return false; char top = stack.pop(); if ((ch == ')' && top != '(') || (ch == '}' && top != '{') || (ch == ']' && top != '[')) { return false; } } } return stack.isEmpty(); }
public static void main(String []argh) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { String input=sc.next(); //Complete the code if(check(input)) System.out.println("true"); else System.out.println("false"); } }
}
Seems like cookies are disabled on this browser, please enable them to open this website
Java Stack
You are viewing a single comment's thread. Return to all comments →
import java.util.*; class Solution{ public static boolean check(String s) { Stack stack = new Stack<>(); for (char ch : s.toCharArray()) {
if (ch == '(' || ch == '{' || ch == '[') { stack.push(ch); } else if (ch == ')' || ch == '}' || ch == ']') { if (stack.isEmpty()) return false; char top = stack.pop(); if ((ch == ')' && top != '(') || (ch == '}' && top != '{') || (ch == ']' && top != '[')) { return false; } } } return stack.isEmpty(); }
}