Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please use Java for the following question Brackets Matches Given a string of pa

ID: 3875077 • Letter: P

Question

Please use Java for the following question

Brackets Matches

Given a string of parentheses, check if the parentheses is valid and display the complete parentheses.

For example:

Given a string value of "(("", it's a invalid parentheses because it's not complete, the complete parentheses should be "()()" because each "(" character shoud be mathced with a ")" closing bracket.

Sample input: "(()(("

Sample output should be : "()()()()".

Because only one set of parentheses is complete at index 1 and 2, so the other three "(" should have a ")" for each one of them.

Sample input: ")(()("

Sample output should be: "()()()()"

Since the first index has ")" so we should add a open bracket for it and index 1 has only "(" so add a close bracket to it and index 2 and 3 are a set of bracket so it's all set, and the last index should have a close bracket.

Sample input : "))(("

Sample output "()()()()"

Since all four indexes are missing parts of brackets so add brackets for them all.

Explanation / Answer

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStreamReader;

/**
*
* @author manB
*/
public class Parentheses {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("INPUT:");
        String input = br.readLine();
        String output = "";
        boolean startParentheses = false;
        for(int i = 0; i < input.length(); i++) {
            if (input.charAt(i) == '(')
                if (startParentheses) {
                    output += ")(";
                }
                else {
                    output += "(";
                    startParentheses = true;
                }
            else if (input.charAt(i) == ')')
                if (startParentheses) {
                    output += ")";
                    startParentheses = false;
                }
                else {
                    output += "()";
                }
        }
        if (startParentheses)
                output += ")";
        System.out.println("OUTPUT");
        System.out.println(output);
    }
}