2ND TRY
Always guarantee that s length is shorter or equal to t to avoid some edge cases
Bug -> "","" should be false -> Since if s.equals(t) should be false
Time O(n) Space O(1)
99.37 %
class Solution {
public boolean isOneEditDistance(String s, String t) {
if (s == null || t == null || s.equals(t) || Math.abs(s.length() - t.length()) > 1) {
return false;
}
if (s.length() > t.length()) {
return isOneEditDistance(t, s);
}
boolean result = true;;
// s is shorter or equals to t
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != t.charAt(i)) {
// i is the last char of s
result = i == s.length() - 1 && i == t.length() - 1
|| s.substring(i + 1, s.length()).equals(t.substring(i + 1, t.length()))
|| s.substring(i, s.length()).equals(t.substring(i + 1, t.length()));
break;
}
}
return result;
}
}
1ST TRY
找到第一个不相等的char
然后比较剩下的
处理substring的时候有一些edge cases需要注意
51.15 %
class Solution {
public boolean isOneEditDistance(String s, String t) {
/* 1. 1 character is different (length equal)
2. 1 character less (s < t)
3. 1 character more (s > t)
*/
if (s == null || t == null) return false;
int sLen = s.length();
int tLen = t.length();
if (Math.abs(sLen - tLen) > 1) return false;
int i;
for (i = 0; i < sLen && i < tLen; i++) {
if (s.charAt(i) != t.charAt(i)) break;
}
if (sLen == tLen) {
if (i == sLen) return false; // 2 strings are equal
return i + 1 == sLen || s.substring(i + 1).equals(t.substring(i + 1));
} else if (sLen < tLen){
if (i == sLen) return true; // string t has 1 more character at the last position
return s.substring(i).equals(t.substring(i + 1));
} else {
if (i == tLen) return true;
return s.substring(i + 1).equals(t.substring(i));
}
}
}
No comments:
Post a Comment