Find String Replace (with.Java)
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).