As I understand your task, you need to find out whether two strings differ in length by one have all the same letters except from only one.
For that, first you need to check if lengths of string meat the requirement and then validate the given string by iterating over its indices and checking its characters against the character of the string from the dictionary.
Your condition that is meant to validate the length is incorrect.
str.length() <= word.length() && str.length() == word.length() + 2
Length of the given string is a distinct value, and it could be either less or equal to the word.length()
or equals to word.length() + 2
. But not both, hence this condition is always false
.
To fix it logical and &&
needs to be replaced with logical or ||
, and in the second part instead ==
you have to apply >=
to caver the whole range of possible invalid sizes. And it can be simplified to
str.length() != word.length() + 1
In order to validate the contents of the given string, you need to introduce a boolean
flag, indicating that a letter in which two strings differ was found.
If the flag is set to true
(i.e. mismatch was found) you need to apply a shift by adding +1
to the index of the given string while checking equality of characters of the two strings, because a single non-matching character shouldn't be taken into account. And if the second mismatch is being encountered, the given string is considered to be invalid - method immediately returns false
.
Only when all characters of the given string are successfully checked against the characters of the string from the dictionary, it's proved to be valid (containing only one non-matching character). Hence, return
statement after the loop yields true
.
public static boolean hasOneAdditionalLetter(String word, String str) {
if (str.length() != word.length() + 1) {
return false;
}
boolean mismatchFound = false;
for (int i = 0; i < str.length() - 1; i++) {
if (!mismatchFound) {
if (str.charAt(i) != word.charAt(i)) {
mismatchFound = true; // first mismatch was found
}
} else if (str.charAt(i + 1) != word.charAt(i)) { // because mismatch was already found shift i + 1 is used
return false; // there's more than mismatch
}
}
return true; // all letter apart from one are the same
}
public static void main(String[] args) {
System.out.println(hasOneAdditionalLetter("apple", "appple")); // true
System.out.println(hasOneAdditionalLetter("horse", "hhorse")); // true
System.out.println(hasOneAdditionalLetter("apple", "applet")); // true
System.out.println(hasOneAdditionalLetter("mountain", "mounYtain")); // true
System.out.println(hasOneAdditionalLetter("fiz", "baz")); // false
}
Output
true - "apple", "appple"
true - "horse", "hhorse"
true - "apple", "applet"
true - "mountain", "mounYtain"
false - "fiz", "baz"
Side-note: method names usually contain a verb because they are meant to represent actions (get
, put
, compute
, remove
, etc.), methods return a boolean
value traditionally start with is
or has
.