Replace a character specific number of times in String Java

Would advise using a pair of loops instead of method’s like replace to fix the parenthesis as order pmatters. Consider a string such as "A)(", though it has the correct number of parenthesis it is still invalid.

String  fixParen(String str) {
        StringBuilder sb = new StringBuilder(str);
        int openCount = 0;
        for(int i=0;i<sb.length();i++){
            switch(sb.charAt(i)){
                case '(': ++openCount; break;
                case ')': if(openCount==0){
                    sb.replace(i, i+1, "");
                    continue;
                }else{
                    --openCount;
                }
            }
        }
        int closedCount =0;
        for(int i=sb.length()-1;i>=0;i--){
            switch(sb.charAt(i)){
                case ')': ++closedCount; break;
                case '(': if(closedCount==0){
                    sb.replace(i,i+1,"" );
                    continue;
                }else{
                    --closedCount;
                }
            }
        }
        return sb.toString();
    }

Leave a Comment