Looking for good programming challenges?

Use the search below to find our solutions for selected questions!

Replace And Remove

Sharing is caring!

Problem Statement
Consider the following two rules that are to be applied to strings over the alphabets: [‘a’, ‘b’, ‘c’, ‘d’]
  • Replace each ‘a’ with ‘dd’
  • Delete each ‘b’
Solution
package problems;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * Remove 'b's and replace 'a's with 'dd'
 */
public class ReplaceAndRemove {
    private static final Set<Character> ALPHABET = new HashSet<Character>(Arrays.asList('a', 'b', 'c', 'd'));

    private static int endIndex(char[] s) {
        for (int i = 0; i < s.length; i++) {
            if (!ALPHABET.contains(s[i])) {
                return i - 1;
            }
        }

        return s.length - 1;
    }


    private static char[] solve(char[] s) {
        int countA = 0;
        int writeIndex = 0;
        for (int i = 0; i < s.length; i++) {
            if (s[i] == 'a') {
                countA++;
            }

            if (s[i] != 'b') {
                s[writeIndex++] = s[i];
            }
        }

        int newLen = ((endIndex(s) + 1) - countA) + 2 * countA;

        writeIndex = newLen - 1;
        int readIndex = endIndex(s);
        while (readIndex >= 0) {
            if (s[readIndex] == 'a') {
                s[writeIndex--] = 'd';
                s[writeIndex--] = 'd';
            } else {
                s[writeIndex--] = s[readIndex];
            }

            readIndex--;
        }

        // Clean any remaining chars
        for (int i = newLen; i < s.length; i++) {
            s[i] = Character.MIN_VALUE;
        }

        return s;
    }

    public static void main(String[] args) {
        char[] s = Arrays.copyOf("bca".toCharArray(), 16);

        System.out.println(new String(solve(s)));
    }
}