Java program to check for Matching Parentheses

In this article, the problem statement is to write a java program that can check and if a string has matching pair of parentheses or not.

For example,

() has matching parenthesis, but (() doesn’t.

For this, we can maintain a counter for the opening parentheses encountered.

When you find an opening parenthesis, add 1 to the counter. Similarly, when you find a closing parenthesis, reduce 1 from the counter. In the end, if the counter is 0, then the parentheses are properly nested.
 

package com.topjavatutorial;

import java.util.Scanner;

public class MatchingParenthesis {

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a string with parenthesis");
    String str = sc.next();
    sc.close();
    System.out.println(isMatchingParenthesis(str));
  }

  private static boolean isMatchingParenthesis(String str){
    int count = 0;
    char[] characters = str.toCharArray();
    for(char ch : characters){
      if(ch == '(')
        count++;
      else{
        count--;
        if(count<0)
          return false;
      }
    }
    if(count==0)
      return true;
    else
      return false;
  }
}

Output :


Enter a string with parenthesis
(())
true

Enter a string with parenthesis
((()((()())
false

 

© 2017, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags