2

I'm writing java code for test balanced parentheses in source code.

Here is the code for check balanced parentheses . In main

  String s = reader.nextLine();
    System.out.println(process(s));

My function

public static boolean process(String s) {
    Stack<Character> stack  = new Stack<Character>();
    for(int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if(c == '[' || c == '(' || c == '{' ) {     
            stack.push(c);
        } else if(c == ']') {
            if(stack.isEmpty() || stack.pop() != '[') {
                System.out.println("yes");
                return false;
            }
        } else if(c == ')') {
            if(stack.isEmpty() || stack.pop() != '(') {

                return false;
            }           
        } else if(c == '}') {
            if(stack.isEmpty() || stack.pop() != '{') {

                return false;
            }
        }

    }
    return stack.isEmpty();
}

It look ok if I only use test case with single line.

input1 : abctex()[]
output: true

Now I got problem, how can check balanced parentheses in each sentences with last index is dot ('.').

For example Input

So when I die (the [first] I will see in (heaven) is a score list).

[ first in ] ( first out ).

Half Moon tonight (At least it is better than no Moon at all].

A rope may form )( a trail in a maze.

Help( I[m being held prisoner in a fortune cookie factory)].

([ (([( [ ] ) ( ) (( ))] )) ]).

 .

.

Output:

true
true
false
false
false
true
true
Nguyen
  • 31
  • 6

1 Answers1

2

You external loop should be not by lines but by sentences. That is read everything up to the dot and use that as input to process. Repeat until the end.

You can read char-by-char like this How do I read input character-by-character in Java?