Contents

Find String Replace (with.Java)

   Oct 23, 2023     2 min read

In this article, we learned how to find the string substitution.

We’ll do this by solving a coding test problem, reflecting on the problem we solved, and learning about other ways to solve it.

Let’s start with the problem

Problem

You are given two strings, myString and pat, consisting of the letters β€œA” and β€œB”.

Complete a solution function that returns 1 if pat is a consecutive substring of the strings myString with β€œA” replaced by β€œB” and β€œB” replaced by β€œA” and 0 otherwise.

Example input and output

myString: β€œABBAA”

pat: β€œAABB”

result: 1

My solution to the problem

class Solution {
    public int solution(String myString, String pat) {
        int answer = 0;
        char[] ch = new char[myString.length()];
        for(int i = 0; i < myString.length(); i++){
            if(myString.charAt(i) == 'A'){
                ch[i] = 'B';
            }else{
                ch[i] = 'A';
            }
        }
        if(String.valueOf(ch).contains(pat)){
            answer = 1;
        }
        } return answer;
    }
}
solution description

public int solution(String myString, String pat):

Begins the definition of the solution method. This method accepts two string arguments, myString and pat, and returns an integer result.

int answer = 0;:

Declare a variable named answer and initialize it to 0. This variable will store the final result.

char[] ch = new char[myString.length()];:

Declare an array of characters, ch, with a length equal to the length of myString. This array will be used to transform myString.

for(int i = 0; i < myString.length(); i++):

Traverse each character in myString using a for loop.

if(myString.charAt(i) == β€˜A’){:

Check if the character at the current index i is β€˜A’.

ch[i] = β€˜B’;:

If it is β€˜A’, convert the character to β€˜B’ and store it in the ch array.

}else:

If not β€˜A’,

ch[i] = β€˜A’;:

Convert that character to β€˜A’ and store it in the ch array.

if(String.valueOf(ch).contains(pat)):

Convert the ch array to a string, and check if the converted string contains the string pat.

answer = 1;:

If pat is contained in ch, set answer to 1.

return answer;:

Finally, return the value of answer.

This code performs a simple string processing operation that converts myString to alternately β€˜A’ and β€˜B’ and then checks if it contains the string pat. The resulting value will be either 1 (contained) or 0 (not contained).