Making B with A (with.Java)
This article looks into the problem of “Making B with A (with.Java)”.
As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.
Let’s look at the problem first.
problem
When strings before and after are given as parameters, complete the solution function to return 1 if you can create after by changing the order of before, and 0 if you cannot.
Restrictions
- 0 < length of before == length of after < 1,000
- Before and after are both lowercase letters.
Input/Output Example
before | after | result |
---|---|---|
“olleh” | “hello” | 1 |
“allpe” | “apple” | 0 |
My solution to the problem
import java.util.Arrays;
class Solution {
public int solution(String before, String after) {
char[] beforeArray = before.toCharArray();
char[] afterArray = after.toCharArray();
Arrays.sort(beforeArray);
Arrays.sort(afterArray);
return Arrays.equals(beforeArray, afterArray) ? 1:0;
}
}
Solved review
First, convert the two input strings before and after into character arrays (char[]).
Sort an array of two characters alphabetically using the Arrays.sort() function.
This will ensure that each character in both strings is aligned.
Use the Arrays.equals() function to determine whether two sorted arrays of characters are equal.
This function compares two arrays for equality and returns true or false.
If the two sorted character arrays are equal, that is, if the two strings contain the same characters, it returns 1.
Otherwise it returns 0.
To simply check whether the input string consists of the same characters, we use a method of sorting and comparing strings.