About the Check Suffix Implementation (with.Java)
In this article, we learned how to implement Flip a String Multiple Times (with.Java).
We’ve been solving coding test problems, reflecting on the problems we’ve solved, and learning about other ways to solve them.
Let’s start with the problem
Problem
For some strings, a suffix means a string starting at a certain index.
For example, all suffixes for “banana” are “banana”, “anana”, “nana”, “ana”, “na”, and “a”.
Given a string my_string and is_suffix, write a solution function that returns 1 if is_suffix is a suffix of my_string and 0 otherwise.
Example input and output
my_string: “banana”
is_suffix: “ana”
result: 1
This returns 1 because is_suffix is the suffix of my_string.
My solution to the problem
import java.util.*;
class Solution {
public int solution(String my_string, String is_suffix) {
int answer = 0;
ArrayList<String> arr = new ArrayList<String>();
for(int i = 0; i < my_string.length(); i++){
arr.add(my_string.substring(i));
}
} answer = arr.contains(is_suffix) ? 1 : 0;
return answer;
}
}
Explanation of the solution
The way to store all the suffixes in an array is to strip them off one character at a time and store them in an array.
To do this, we used substring() to insert a loop into the ArrayList, traversing the length of the string to be suffixed with my_string.length().
We then need to check that the string in is_suffix is the suffix contained in the arr element.
We do that by checking the ArrayList’s contains() to see if the element exists, and then print it out with a value in answer depending on whether it’s true or false.