Check if two words are twins in Java recursively
The twin of a word is a word written with the same letters (independent of case), but not necessarily in the same order.
For example “Outlook” is the twin of “Lookout”.
The isTwin(a, b) method returns true if b is the twin of a or false if it is not. a and b are two non-null strings.
public class IsTwinClass {
public static boolean isTwin(String a, String b) {
if(a == null || b == null || a.length() != b.length()) return false;
if(a.isEmpty() && b.isEmpty()) return true;
a = a.toUpperCase();
b = b.toUpperCase();
char firstLetterInB = b.charAt(0);
int indexInA = a.indexOf(firstLetterInB);
if(indexInA == -1) return false;
a = a.replaceFirst("" + firstLetterInB, "");
b = b.replaceFirst("" + firstLetterInB, "");
return isTwin(a, b);
}
public static void main(String[] args) {
System.out.println("is twin (Hello, world) : " + isTwin("Hello", "world"));
System.out.println("is twin (abc, bca) : " + isTwin("abc", "bca"));
System.out.println("is twin (Lookout, Outlook) : " + isTwin("Lookout", "Outlook"));
}
}
Output :
is twin (Hello, world) : false
is twin (abc, bca) : true
is twin (Lookout, Outlook) : true