当前位置:网站首页>[LeetCode]161. 相隔为 1 的编辑距离
[LeetCode]161. 相隔为 1 的编辑距离
2022-06-27 19:35:00 【阿飞算法】
题目
给定两个字符串 s 和 t,判断他们的编辑距离是否为 1。
注意:
满足编辑距离等于 1 有三种可能的情形:
往 s 中插入一个字符得到 t
从 s 中删除一个字符得到 t
在 s 中替换一个字符得到 t
样例
示例 1:
输入: s = "ab", t = "acb"
输出: true
解释: 可以将 'c' 插入字符串 s 来得到 t。
示例 2:
输入: s = "cab", t = "ad"
输出: false
解释: 无法通过 1 步操作使 s 变为 t。
示例 3:
输入: s = "1203", t = "1213"
输出: true
解释: 可以将字符串 s 中的 '0' 替换为 '1' 来得到 t。
方法1:比较字符串
public static void main(String[] args) {
_1st handler = new _1st();
String s = "ab", t = "acb";
Assert.assertTrue(handler.isOneEditDistance(s, t));
s = "cab";
t = "ad";
Assert.assertFalse(handler.isOneEditDistance(s, t));
s = "1203";
t = "1213";
Assert.assertTrue(handler.isOneEditDistance(s, t));
}
public boolean isOneEditDistance(String s, String t) {
int sn = s.length(), tn = t.length();
//维持s的长度小于t
if (sn > tn) {
return isOneEditDistance(t, s);
}
if (tn - sn > 1) return false;//相隔大于1时,返回false
for (int i = 0; i < sn; i++) {
if (s.charAt(i) != t.charAt(i)) {
//s与t的长度相同,比较后面的
if (sn == tn) {
return s.substring(i + 1).equals(t.substring(i + 1));
} else {
//s与t的长度不同 s的字符短
return s.substring(i).equals(t.substring(i + 1));
}
}
}
return sn + 1 == tn;
}
边栏推荐
- Go从入门到实战——package(笔记)
- Bit.Store:熊市漫漫,稳定Staking产品或成主旋律
- 100 important knowledge points that SQL must master: creating calculation fields
- Is it safe to open an account and buy stocks? Who knows
- At 19:00 on Tuesday evening, the 8th live broadcast of battle code Pioneer - how to participate in openharmony's open source contribution in multiple directions
- Quick excel export
- SQL必需掌握的100个重要知识点:IN 操作符
- Codeforces Global Round 14
- vmware虚拟机PE启动
- List of language weaknesses --cwe, a website worth learning
猜你喜欢
随机推荐
Tiktok's interest in e-commerce has hit the traffic ceiling?
100 important knowledge points for SQL: in operator
Codeforces Round #722 (Div. 2)
GBase 8a OLAP函数group by grouping sets的使用样例
Go from entry to practice -- CSP concurrency mechanism (note)
Galaxy Kirin system LAN file sharing tutorial
Codeforces Round #723 (Div. 2)
excel读取文件内容方法
神奇的POI读取excel模板文件报错
Flask----应用案例
SQL必需掌握的100个重要知识点:过滤数据
Use the storcli tool to configure raid. Just collect this article
抖音的兴趣电商已经碰到流量天花板?
有时间看看ognl表达式
关于异常处理的知识整理
Go从入门到实战——仅执行一次(笔记)
Common methods of string class
Go from starting to Real - Interface (note)
Set code exercise
linux下安装oracle11g 静默安装教程









