One Edit Distance
https://leetcode.com/problems/one-edit-distance/description/
Given two strings S and T, determine if they are both one edit distance apart.
Thoughts
[https://discuss.leetcode.com/topic/30308/my-clear-java-solution-with-explanation] 要求是必须one distance apart. 一共三种情况, 某位上不一样, s缺一个或t缺一个. 遍历, 当到i时两个字符不一样就分这三种情况讨论.
Code
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;
}
}
Analysis
时间复杂度O(N).
Last updated
Was this helpful?