资讯专栏INFORMATION COLUMN

Leetcode[161] One Edit Distance

周国辉 / 3231人阅读

摘要:复杂度思路考虑如果两个字符串的长度,是肯定当两个字符串中有不同的字符出现的时候,说明之后的字符串一定要相等。的长度比较大的时候,说明的时候,才能保证距离为。

LeetCode[161] One Edit Distance

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

String

复杂度
O(N),O(1)

思路
考虑如果两个字符串的长度 > 1,是肯定return false;
当两个字符串中有不同的字符出现的时候,说明之后的字符串一定要相等。

abc
ac

s的长度比较大的时候,说明s.substring(i + 1).equals(t.substring(i))的时候,才能保证距离为1。

ac
abc

t的长度比较大的时候,说明t.substring(i + 1).equals(s.substring(i)), 才能保证距离为1。

abe
ace

当剩下的字符串距离相等的时候,说明只有当剩下的字符串相等的时候,才能保证距离为1.

代码

public boolean isOneEditDistance(String s, String t) {
    for(int i = 0;i < Math.min(s.length(), t.length()); i ++) {
        if(s.charAt(i) != t.charAt(i)) {
            if(s.length() == t.length()) {
                return s.substring(i + 1).equals(t.substring(i + 1));
            }
            else if(s.length() > t.length()) {
                return s.substring(i + 1).equals(t.substring(i));
            }
            else {
                return s.substring(i).equals(t.substring(i + 1));
            }
        }
    }
    return Math.abs(s.length(), t.length()) == 1;
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/66139.html

相关文章

  • [Leetcode] One Edit Distance 编辑距离为一

    摘要:比较长度法复杂度时间空间思路虽然我们可以用的解法,看是否为,但中会超时。这里我们可以利用只有一个不同的特点在时间内完成。 One Edit Distance Given two strings S and T, determine if they are both one edit distance apart. 比较长度法 复杂度 时间 O(N) 空间 O(1) 思路 虽然我们可以用...

    lewinlee 评论0 收藏0
  • LeetCode[72] Edit Distance

    摘要:复杂度思路考虑用二维来表示变换的情况。如果两个字符串中的字符相等,那么如果两个字符串中的字符不相等,那么考虑不同的情况表示的是,从字符串到的位置转换到字符串到的位置,所需要的最少步数。 LeetCode[72] Edit Distance Given two words word1 and word2, find the minimum number of steps require...

    call_me_R 评论0 收藏0
  • [Leetcode] Edit Distance 最小编辑距离

    摘要:动态规划复杂度时间空间思路这是算法导论中经典的一道动态规划的题。 Edit Distance Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.) You h...

    zhangke3016 评论0 收藏0
  • [LintCode/LeetCode] Edit Distance

    摘要:构造数组,是的,是的,是将位的转换成位的需要的步数。初始化和为到它们各自的距离,然后两次循环和即可。 Problem Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 s...

    snowell 评论0 收藏0
  • leetcode72. Edit Distance

    摘要:题目要求输入两个字符串和,允许对进行插入,删除和替换的操作,计算出将转化为所需要的最少的操作数。其中存储的是转换为的最小步数。首先从边缘情况开始考虑。只要在此基础上再进行一次插入操作即可以完成转换。 题目要求 Given two words word1 and word2, find the minimum number of steps required to convert wor...

    venmos 评论0 收藏0

发表评论

0条评论

周国辉

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<