[leetcode]161. 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

思路

此题可算是[leetcode]72. Edit Distance 最少编辑步数的一个拆分简化版本

代码

 class Solution {
public boolean isOneEditDistance(String s, String t) {
int m = s.length(), n = t.length();
if(m == n) return isOneModified(s, t);
if(m - n == 1) return isOneDeleted(s, t);
if(n - m == 1) return isOneDeleted(t, s);
// 长度差距大于2直接返回false
return false;
} private boolean isOneModified(String s, String t){
boolean modified = false;
// 看是否只修改了一个字符
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) != t.charAt(i)){
if(modified) return false;
modified = true;
}
}
return modified;
} public boolean isOneDeleted(String longer, String shorter){
// 找到第一组不一样的字符,看后面是否一样
for(int i = 0; i < shorter.length(); i++){
if(longer.charAt(i) != shorter.charAt(i)){
return longer.substring(i + 1).equals(shorter.substring(i));
}
}
return true;
}
}
上一篇:【LeetCode】161. One Edit Distance


下一篇:[LeetCode] 161. One Edit Distance_Medium