Find the longest substring ending in a specific string (with.Java)
This is a recap of the “Find the longest substring ending in a specific string” problem.
We’re going to look at it as a coding test problem, provide a retrospective on how we solved it, and explore other ways to solve it.
Let’s start with the problem
Problem
You are given the strings myString and pat.
Complete a solution function that finds and returns the longest substring of myString that ends in pat.
Example input and output
myString | pat | result |
---|---|---|
“AbCdEFG” | “dE” | “AbCdE” |
“AAAAaaaa” | “a” | “AAAAaaaa” |
My solution to the problem
class Solution {
public String solution(String myString, String pat) {
StringBuilder answer = new StringBuilder();
StringBuilder answer1 = new StringBuilder();
for(int i = 0; i < myString.length(); i++){
answer.append(myString.charAt(i));
}
} int count = answer.lastIndexOf(pat);
answer1.append(answer.substring(0,count));
for(int j = 0; j < pat.length(); j++){
answer1.append(pat.charAt(j));
}
} return answer1.toString();
Solution
StringBuilder answer = new StringBuilder(); and StringBuilder answer1 = new StringBuilder();: Create two StringBuilder objects answer and answer1. These objects help us manipulate strings efficiently.
for(int i = 0; i < myString.length(); i++): Iterate over the input string myString, adding each character to answer. This ensures that answer contains the contents of myString.
int count = answer.lastIndexOf(pat);: Find the last occurrence of the string pat in the answer string and store it in count.
answer1.append(answer.substring(0, count)): Add the substring from the answer string to the last occurrence of the pat string to answer1. This substring is the string before the pat.
for(int j = 0; j < pat.length(); j++): Add each character of the pat string to answer1.
return answer1.toString();: Convert the final assembled answer1 string to a string and return it.
This code finds the last occurrence of pat in the input string myString, replaces that part of the string with pat, and returns it.