Validate Balanced Parentheses

You have a string consisting of open and closed parentheses, but parentheses may be imbalanced. Make the parentheses balanced and return the new string.

Solution)

Check the open and closed parentheses.

public String validateBalancedParentheses(String s) {
    int count = 0, idx = 0;
    StringBuffer sb = new StringBuffer();
    for (char c : s.toCharArray()) {
        if (c == '(') {
            if (count == 0)
                idx = sb.length();
            c++;
            sb.append(c);
        } else if (c == ')') {
            c--;
            if (c < 0) {
                sb.insert(idx,'(');
            sb.append(c);
        }
    }
    for (int i = 0; i < count; i++) {
        sb.append(')');
    }
    return sb.toString();
}

results matching ""

    No results matching ""