Replace all occurrences of string AB with C without using extra space in Java
Replacing all occurrences of a given substring in a string entails replacing each instance with another string, affecting the original string's contents.
Example:
Input: str = "TutorialABExample"
Output: String with 'AB' replaced by 'C': TutorialCExample
Explanation:
Replace "AB" at index 8-9 with "C": TutorialCExample
Approach: Brute Force
The Java program introduces a method named replaceABwithC(), which replaces all instances of AB in a string with C.
FileName: ReplaceABwithC.java
public class ReplaceABwithC { public static String replaceABwithC(String input) { return input.replaceAll("AB", "C"); } public static void main(String[] args) { String str = "TutorialABExample"; String replaced = replaceABwithC(str); System.out.println("String with 'AB' replaced by 'C': " + replaced); } }
Output:
String with 'AB' replaced by 'C': TutorialCExample
Complexity Analysis: The time and space complexity is O(n), where n is the length of the input string.
Approach: Using Two Pointers
The Java code specifies the replaceABwithC() method, which iterates through each letter in the input string, replacing AB with C by directly altering the character array and nullifying the B. It then returns the updated string with no null characters.
FileName: ReplaceABwithC1.java
public class ReplaceABwithC1 { public static String replaceABwithC(String input) { char[] chars = input.toCharArray(); for (int i = 0; i < chars.length - 1; i++) { if (chars[i] == 'A' && chars[i + 1] == 'B') { chars[i] = 'C'; chars[i + 1] = '