Skip to content
Advertisement

Best way to remove characters at certain positions in a Java string or stringbuilder

process_str(StringBuilder copy, List<Integer> idxList) {
        for(int i = 0; i < idxList.size(); ++i) {
            int pos  = idxList.get(i);
            copy.setCharAt(pos, '$');
        }
        StringBuilder output = new StringBuilder();
        for(int i = 0; i < copy.length(); ++i) {
            char ch = copy.charAt(i);
            if(ch != '$')
                output.append(ch);
        }
        return output.toString();
}

Constraint – $ does not appear in the input string. Is there a simpler way to do this?

Advertisement

Answer

You can remove the first loop like this:

process_str(StringBuilder copy, List<Integer> idxList) {
    StringBuilder output = new StringBuilder();
    for(int i = 0; i < copy.length(); ++i) {
        char ch = copy.charAt(i);
        if (idxList.contains(i))
            output.append(ch);
    }
    return output.toString();
}

The overall time complexity might be different depending on what type of List you use.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement