Replace Occurances of the given string

package strings;

/*
Given a string str that may contain one more occurrences of “AB”. 
Replace all occurrences of “AB” with “C” in str.

This should be in the same array. 
Solution should be optimized
Dont try to shift entire elements or something.

Examples:

Input  : str = "helloABworld"
Output : str = "helloCworld"

Input  : str = "fghABsdfABysu"
Output : str = "fghCsdfCysu"
*/


public class ReplaceOccurances {
    static char[] replace(char[] str) {
        int len = str.length;
        if (len < 2)
            return str;

        int i = 0; // Index in modified string
        int j = 0; // Index in original string

        // Traverse string
        while (j < len - 1) {
            // Replace occurrence of "AB" with "C"
            if (str[j] == 'A' && str[j + 1] == 'B') {
                // Increment j by 2
                j = j + 2;
                str[i++] = 'C';
                continue;
            }
            str[i++] = str[j++];
        }

        if (j == len - 1)
            str[i++] = str[j];

        // add a null character to terminate string
        str[i] = '\0';
        return str;
    }

    public static void main(String[] args) {
        String str = "helloABworldABGfG";
        System.out.println(replace(str.toCharArray()));

    }
}


/*

An efficient solution is to keep track of two indexes, one for modified string (i in below code) 
and other for original string (j in below code). If we find “AB” at current index j, 
we increment j by 2 and i by 1. Otherwise we increment both and copy character from j to i.

Below is implementation of above idea.


*/

Comments

Popular posts from this blog

Java important topics list for interviews

Tough Sql practise questions for interviews involving SELECT queries - Part 2

DBMS important topics list for interviews

Program to find number lines and words in a given file

Tough Sql practise questions for interviews involving SELECT queries - Part 1

Producer Consumer Problem with Blocking Queue in Java.

Animation for String search - KMP Algorithm

Interactive Data Structure visualizations/animations for algorithms