Balanced Parenthesis

☞ Check whether string is a balanced parenthesized expression.
Sample Input1
(()())
Sample Output1
Valid
Sample Input2
(()()
Sample Output2
Invalid
SOURCE CODE:
import java.io.*;
import java.util.*;
class BalancedParenthesis{
public static void main(String args[]){
    String str;
    int i,j=0,count=0;
    Scanner in = new Scanner(System.in);
    str = in.nextLine();
char top[] = new char[str.length()];
for(i=0;i<str.length();i++){
        if(str.charAt(i)=='(')
            top[j++]=str.charAt(i);
        else if(str.charAt(i)==')' && top[j-1]=='(')
            j--;
    }
    if(j==0)
        System.out.print("Valid");
    else
        System.out.print("Invalid");
}
}

No comments:

Post a Comment

Total Pageviews