Java Stack Hackerrank Solution

 Java Stack Hackerrank Solution


For Explanation watch video: 


Sample Input

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

Sample Output

true
true
false
true
Code:
import java.util.*;
class Solution{
    
    public static void main(String []argh)
    {
        Scanner sc = new Scanner(System.in);
        
        while (sc.hasNext()) {
            String input=sc.next();
            System.out.println(valid(input));
        }
        
    }
    static boolean valid(String s){
        Stack<Character> st = new Stack<>();
        for(int i=0;i<s.length();i++){
            char ch = s.charAt(i);
            if(ch=='(' || ch=='[' || ch=='{'){
                st.push(ch);
            }else if(st.isEmpty()){   
                  return false;
            }else{
                char top = st.pop();
         if((top=='(' && ch!=')') || (top=='[' && ch!=']')|| (top=='{' && ch!='}')){
                  return false;
            }
            }
        }
        return st.isEmpty();
    }
}



Comments

Popular posts from this blog

Print Prime Numbers Hackerrank Solution - PL/SQL

how to store html form data in mysql database using hibernate