Wednesday 5 August 2015

Bracket matching problem

Suppose you had a string which contains only '(' and ')' characters. Write a program to check whether it forms a valid expression (or) not.

For example
(()()()) is valid expression
()( is invalid expression.

Using a stack we can solve this problem.

1. For each character in the string
    If the symbol is '('
         push it on to the stack
   else
        If the stack is empty
            return false
       Pop top element

2. At the end if stack is empty, return true, else false.
import java.util.LinkedList;
import java.util.Objects;

public class BracketMatcher {

 public static boolean isValidExpression(String str) {
  Objects.nonNull(str);

  LinkedList<Character> list = new LinkedList<>();

  for (int i = 0; i < str.length(); i++) {
   if (str.charAt(i) == '(') {
    list.add('(');
   } else {
    if (list.isEmpty())
     return false;
    list.pop();
   }
  }

  if (list.isEmpty())
   return true;

  return false;
 }
}


Following is the junit test case for above program.
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class BracketMatcherTest {

 @Test
 public void test1() {
  assertTrue(BracketMatcher.isValidExpression("()()()()"));
  assertTrue(BracketMatcher.isValidExpression("((())())()()()"));

  assertFalse(BracketMatcher.isValidExpression("()()()())"));
  assertFalse(BracketMatcher.isValidExpression("(()()()()"));
 }
}


No comments:

Post a Comment