Oracle Coding Interview

Anonymous User
512
Apr 11, 2024
Apr 11, 2024

Given a string - sequence of brackets, return the number of valid ways we can insert '(' to make the sequence of brackets as a valid.

Example:

Input : "(())())()" Output: 7
Input: "(()))" Output: 5

image

Better solutions are welcome :)

Time Complexity: O(n^2)

public class Solution {

	public static void main(String[] args) {
		System.out.println(countBracketSequence("(())())()"));// 7
		System.out.println(countBracketSequence("(()))"));// 5
	}

	public static int countBracketSequence(String s) {
		int total = 0;
		for (int i = 0; i < s.length(); i++) {
			StringBuffer sb = new StringBuffer(s);
			sb.insert(i, '(');
			if (isValidBracket(sb.toString())) {
				total++;
			}
		}
		return total;
	}

	public static boolean isValidBracket(String s) {
		Stack<Character> stack = new Stack<>();

		for (char c : s.toCharArray()) {
			if (c == '(') {
				stack.push(c);
			} else if (!stack.isEmpty() && c == ')' && stack.peek() == '(') {
				stack.pop();
			}
		}
		return stack.isEmpty();
	}
}
Comments (5)