LeetCode-One Edit Distance

本文提供两种解决方案来判断两个字符串是否仅相隔一个编辑距离。方案一通过替换和插入操作检查,方案二则通过子串比较简化流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given two strings S and T, determine if they are both one edit distance apart.

Solution 1:

 1 public class Solution {
 2     public boolean isOneEditDistance(String s, String t) {
 3         if ((s.isEmpty() && t.isEmpty()) || Math.abs(s.length() - t.length()) > 1)
 4             return false;
 5 
 6         if (s.length() == t.length()) {
 7             return isOneReplace(s, t);
 8         }
 9 
10         if (s.length() > t.length()) {
11             return isOneInsert(t, s);
12         } else {
13             return isOneInsert(s, t);
14         }
15     }
16 
17     public boolean isOneReplace(String s, String t) {
18         boolean foundDiff = false;
19         for (int i = 0; i < s.length(); i++)
20             if (s.charAt(i) != t.charAt(i)) {
21                 if (foundDiff)
22                     return false;
23                 foundDiff = true;
24             }
25         return foundDiff;
26 
27     }
28 
29     public boolean isOneInsert(String small, String large) {
30         boolean hasSkip = false;
31         int p1 = 0, p2 = 0;
32         while (p1 < small.length() && p2 < large.length()) {
33             if (small.charAt(p1) != large.charAt(p2)) {
34                 if (hasSkip)
35                     return false;
36                 hasSkip = true;
37                 p2++;
38             } else {
39                 p1++;
40                 p2++;
41             }
42         }
43         return true;
44     }
45 }

NOTE: this solution is too much for this question. We can simply fetch substring and compare.

Solution 2:

 1 public class Solution {
 2     public boolean isOneEditDistance(String s, String t) {
 3         int m = s.length();
 4         int n = t.length();
 5         if (Math.abs(m - n) > 1) {
 6             return false;
 7         }
 8 
 9         int len = Math.min(m, n);
10         for (int i = 0; i < len; i++) {
11             if (s.charAt(i) != t.charAt(i)) {
12                 boolean result = s.substring(i).equals(t.substring(i + 1));
13                 result = result || s.substring(i + 1).equals(t.substring(i));
14                 result = result || s.substring(i + 1).equals(t.substring(i + 1));
15                 return result;
16             }
17         }
18         return Math.abs(m - n) == 1;
19     }
20 }

 

转载于:https://www.cnblogs.com/lishiblog/p/5817839.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值