当前位置:网站首页>[LeetCode]161. Edit distance of 1
[LeetCode]161. Edit distance of 1
2022-06-27 21:50:00 【A Fei algorithm】
subject
Given two strings s and t, Judge whether their editing distance is 1.
Be careful :
The editing distance is equal to 1 There are three possible situations :
Go to s Insert a character in to get t
from s Delete a character to get t
stay s Replace a character in to get t
Examples
Example 1:
Input : s = "ab", t = "acb"
Output : true
explain : Can be 'c' Insert string s To get t.
Example 2:
Input : s = "cab", t = "ad"
Output : false
explain : Unable to get 1 Step operation s Turn into t.
Example 3:
Input : s = "1203", t = "1213"
Output : true
explain : You can string s Medium '0' Replace with '1' To get t.
Method 1: Compare strings
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();
// maintain s The length of is less than t
if (sn > tn) {
return isOneEditDistance(t, s);
}
if (tn - sn > 1) return false;// Greater than 1 when , return false
for (int i = 0; i < sn; i++) {
if (s.charAt(i) != t.charAt(i)) {
//s And t The same length , Compare the following
if (sn == tn) {
return s.substring(i + 1).equals(t.substring(i + 1));
} else {
//s And t The length is different s The characters of are short
return s.substring(i).equals(t.substring(i + 1));
}
}
}
return sn + 1 == tn;
}
边栏推荐
猜你喜欢

今晚战码先锋润和赛道第2期直播丨如何参与OpenHarmony代码贡献

让马化腾失望了!Web3.0,毫无希望

STM32CubeIDE1.9.0\STM32CubeMX 6.5 F429IGT6加LAN8720A,配置ETH+LWIP

Codeforces Round #716 (Div. 2)

PCIE知识点-008:PCIE switch的结构

Go from starting to Real - Interface (note)

Process control task

语言弱点列表--CWE,一个值得学习的网站
![[LeetCode]动态规划解拆分整数I[Silver Fox]](/img/18/8dc8159037ec1262444db8899cde0c.png)
[LeetCode]动态规划解拆分整数I[Silver Fox]

Go from introduction to actual combat - panic and recover (notes)
随机推荐
石子合并问题分析
Go从入门到实战——CSP并发机制(笔记)
After being forced to develop the app within 20 days, the group was laid off, and the technical director angrily criticized it: I wish "closure as soon as possible!"
创建对象时JVM内存结构
Acwing周赛57-最长连续子序列-(二分or树状数组)
Scrum和看板的区别
C语言程序设计详细版 (学习笔记1) 看完不懂,我也没办法。
io流代码
Installing Oracle11g under Linux
excel读取文件内容方法
ICML2022 | 可扩展深度高斯马尔可夫随机场
SQL必需掌握的100个重要知识点:过滤数据
GBase 8a OLAP函数group by grouping sets的使用样例
Go from introduction to practice - Interface (notes)
GBase 8a OLAP分析函数cume_dist的使用样例
猜拳游戏专题训练
Go从入门到实战——协程机制(笔记)
关于异常处理的知识整理
Flask----应用案例
数组作业题