Find String Contains Valid Parentheses or Not


  1. boolean isValid(String str)
  2. {
  3.    Stack<Character> st=new Stack<Character>();
  4.    for(char ch:str.toCharArray())
  5.    {  
  6.      if(ch=='['||ch=='('||ch=='{')
  7.       {
  8.             st.push(st);
  9.       }else if(ch==')'&&!st.isEmpty()&&st.peek()=='('){
  10.          st.pop():
  11.      }else if(ch=='}'&&!st.isEmpty()&&st.peek()=='}'){
  12.          st.pop():
  13.      }else if(ch=='}'&&!st.isEmpty()&&st.peek()=='{'){
  14.          st.pop():
  15.      }else{
  16.        return false;
  17.       }
  18.    }
  19.    return st.isEmpty();
  20. }

Comments

Popular posts from this blog

BYTE STUFFING PROGRAM USING C

Rotate a matrix 270 degree AntiClockWise

Finding the length of connected cells of 1's (regions) in an matrix of 1's and 0's