As this is a problem involved with ordering, we can't use HashMap...
Super clear solution:
Similar to finding the exact different position, but uses substring and simplified a lot
class Solution {
public boolean isOneEditDistance(String s, String t) {
for (int i = 0; i < Math.min(s.length(), t.length()); i++) {
if (s.charAt(i) != t.charAt(i)) {
if (s.length() == t.length()) {
return s.substring(i + 1).equals(t.substring(i + 1));
}
else if (s.length() < t.length()) {
return s.substring(i).equals(t.substring(i + 1));
}
else return s.substring(i + 1).equals(t.substring(i));
}
}
return (Math.abs(s.length() - t.length()) == 1);
}
}
So many corner cases in this problem.
Like "" and "a"
"a" and "A"
And notice here we only compared the shorter length, and we should add a condition in the end to return the result for those that all the checked elements are same, such as "abc" and "ab". "abcd" and "ab".
As this is a problem involved with ordering, we can't use HashMap...
Super clear solution: Similar to finding the exact different position, but uses substring and simplified a lot
So many corner cases in this problem. Like "" and "a" "a" and "A"
And notice here we only compared the shorter length, and we should add a condition in the end to return the result for those that all the checked elements are same, such as "abc" and "ab". "abcd" and "ab".