File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ import  java .util .Scanner ;
2+ import  java .util .Stack ;
3+ 
4+ public  class  validParentheses  {
5+ 
6+     public  static  void  main (String [] args ) {
7+         
8+         Scanner  sc  = new  Scanner (System .in );
9+         
10+         // Get input 
11+         System .out .println ("Enter a string of brackets:" );
12+         String  str  = sc .nextLine ();
13+         
14+         boolean  isValid  = checkValidParentheses (str );
15+         
16+         if  (isValid ) {
17+             System .out .println ("The parentheses are valid!" );
18+         } else  {
19+             System .out .println ("The parentheses are NOT valid!" );
20+         }
21+     }
22+     
23+     
24+     public  static  boolean  checkValidParentheses (String  s ) {
25+         Stack <Character > stack  = new  Stack <>();
26+         
27+         for  (char  ch  : s .toCharArray ()) {
28+             if  (ch  == '('  || ch  == '{'  || ch  == '[' ) {
29+                 stack .push (ch );
30+             } else  if  (ch  == ')'  || ch  == '}'  || ch  == ']' ) {
31+                 if  (stack .isEmpty ()) return  false ;
32+                 
33+                 char  top  = stack .pop ();
34+                 
35+                 if  ((ch  == ')'  && top  != '(' ) ||
36+                     (ch  == '}'  && top  != '{' ) ||
37+                     (ch  == ']'  && top  != '[' )) {
38+                     return  false ;
39+                 }
40+             }
41+         }
42+         
43+         return  stack .isEmpty ();
44+     }
45+ }
46+ 
 
 
   
 
     
   
   
          
    
    
     
    
      
     
     
    You can’t perform that action at this time.
  
 
    
  
    
      
        
     
       
      
     
   
 
    
    
  
 
  
 
     
    
0 commit comments