LeetCode – Refresh – One Edit Distance

本文介绍了一种用于检查两个字符串是否仅相差一个编辑操作的算法。该算法通过遍历两个字符串,对比字符差异并判断是否可以通过一次插入、删除或替换操作使两字符串相等。文章提供了详细的C++实现代码。

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

Scanning from start to end. If find a mismatch and one is larger size, keep search from the previous char of shorter one.

Finally check whether found a mismatch OR still have a larger size string.

 1 class Solution {
 2 public:
 3     bool isOneEditDistance(string s, string t) {
 4         if (s.size() > t.size()) {
 5             return isOneEditDistance(t, s);
 6         }
 7         
 8         if (t.size() - s.size() > 1) return false;
 9         bool found = false;
10         for (int i = 0, j = 0; j < t.size(); i++, j++) {
11             if (s[i] != t[j]) {
12                 if (found) return false;
13                 found = true;
14                 if (t.size() > s.size()) {
15                     i--;
16                 }
17             }
18         }
19         return (found || t.size() > s.size());
20     }
21 };

 

转载于:https://www.cnblogs.com/shuashuashua/p/4355656.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值