Skip to main content

Valid Parentheses Question Solution in java

  Valid Parentheses Question Solution in java



Code:

 import java.util.*;
class Test
{
public static void main(String[] args){
Scanner scn = new Scanner(System.in);
String s = scn.next();
System.out.println(isValid(s));
}
public static boolean isValid(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(ch==')'&&top!='('){
                    return false;
                }
if(ch=='}'&&top!='{'){
                    return false;
                }
if(ch==']'&&top!='['){
                    return false;
                }
            }
        }
return st.isEmpty();
    }
}

Comments