LeetCode 161. One Edit Distance
原题链接在这里:https://leetcode.com/problems/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:
- Insert a character into s to get t
- Delete a character from s to get t
- 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, return false. 若是长度相差等于1, 遇到不同char时, 长的那个向后挪一位. 若是长度相等, 遇到不同char时同时向后挪一位.
出了loop还没有返回,就是到目前为止都相同,那么看长度差是不是等于1. 这里等于0表示完全相同也不可以.
Time Complexity: O(Math.min(len1, len2)).
Space: O(1).
AC Java:
1 public class Solution { 2 public boolean isOneEditDistance(String s, String t) { 3 if(s == null || t == null){ 4 return false; 5 } 6 int len1 = s.length(); 7 int len2 = t.length(); 8 for(int i = 0; i < Math.min(len1, len2); i++){ 9 if(s.charAt(i) != t.charAt(i)){ 10 if(len1 == len2){ 11 return s.substring(i+1).equals(t.substring(i+1)); 12 }else if(len1 > len2){ 13 return s.substring(i+1).equals(t.substring(i)); 14 }else{ 15 return s.substring(i).equals(t.substring(i+1)); 16 } 17 } 18 } 19 return Math.abs(len1-len2) == 1; 20 } 21 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?