LeetCode One Edit Distance

时间:2023-03-09 00:19:28
LeetCode One Edit Distance

原题链接在这里:https://leetcode.com/problems/one-edit-distance/

题目:

Given two strings s and t, determine if they are both one edit distance apart.

Note:

There are 3 possiblities to satisify one edit distance apart:

  1. Insert a character into s to get t
  2. Delete a character from s to get t
  3. Replace a character of s to get t

Example 1:

Input: s = "ab", t = "acb"
Output: true
Explanation: We can insert 'c' into s to get t.

Example 2:

Input: s = "cab", t = "ad"
Output: false
Explanation: We cannot get t from s by only one step.

Example 3:

Input: s = "1203", t = "1213"
Output: true
Explanation: We can replace '0' with '1' to get t.

题解:

若是长度相差大于1, return false. 若是长度相差等于1, 遇到不同char时, 长的那个向后挪一位. 若是长度相等, 遇到不同char时同时向后挪一位.

出了loop还没有返回,就是到目前为止都相同,那么看长度差是不是等于1. 这里等于0表示完全相同也不可以.

Time Complexity: O(Math.min(len1, len2)).

Space: O(1).

AC Java:

 public class Solution {
public boolean isOneEditDistance(String s, String t) {
if(s == null || t == null){
return false;
}
int len1 = s.length();
int len2 = t.length();
for(int i = 0; i < Math.min(len1, len2); i++){
if(s.charAt(i) != t.charAt(i)){
if(len1 == len2){
return s.substring(i+1).equals(t.substring(i+1));
}else if(len1 > len2){
return s.substring(i+1).equals(t.substring(i));
}else{
return s.substring(i).equals(t.substring(i+1));
}
}
}
return Math.abs(len1-len2) == 1;
}
}

类似Edit Distance.