【LeetCode】面试题 01.05. 一次编辑

1. 题目描述

字符串有三种编辑操作:插入一个字符、删除一个字符或者替换一个字符。 给定两个字符串,编写一个函数判定它们是否只需要一次(或者零次)编辑。

示例 1:

输入:
first = “pale”
second = “ple”
输出: True

示例 2:

输入:
first = “pales”
second = “pal”
输出: False

来源:力扣(LeetCode
链接:https://leetcode-cn.com/problems/one-away-lcci

2. 解答

最初的思路为同步遍历这两个字符串就可以了。比如下面的示例:
在这里插入图片描述
当然,首先需要做一些简单的长度判断。

class Solution {
    
    
    public boolean oneEditAway(String first, String second) {
    
    
        // todo 边界处理
        if(null == first || null == second) return false;
        int firstLen = first.length();
        int secondLen = second.length();
        if(Math.abs(firstLen - secondLen) >= 2) return false;
        // todo 单独判断相等,两次不等就为假
        if(firstLen == secondLen){
    
    
            int count = 0;
            for (int i = 0; i < firstLen; i++) {
    
    
                if(first.charAt(i) != second.charAt(i)){
    
    
                    count++;
                    if(count >= 2) return false;
                }
            }
            return true;
        }
        // todo 使first较长
        if(firstLen < secondLen){
    
    
            String temp = first;
            first = second;
            second = temp;
            firstLen = secondLen;
        }
        if(firstLen == 1) return true;
        
        // todo 让first跳过一次,如果跳两次就为假
        int count = 0, j = 0;
        for (int i = 0; i < firstLen; i++) {
    
    
            if(j < second.length() && first.charAt(i) == second.charAt(j)){
    
    
                j++;
            }else{
    
    
                count += 1;
                if(count >= 2) return false;
            }
        }
        return true;
    }
}

Thanks

おすすめ

転載: blog.csdn.net/qq_26460841/article/details/120945924