栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

LeetCode 面试题 01.05 一次编辑[模拟 双指针] HERODING的LeetCode之路

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode 面试题 01.05 一次编辑[模拟 双指针] HERODING的LeetCode之路


解题思路:
非常简单的一道模拟题,首先如果字符串长度差距1以上返回false,字符串相等返回true,定义双指针分别遍历两个字符串,遇到对应位置相等继续,不等又分两种情况,如果是长度相同,那么都跳一位,不等,长的跳一位,短的不动,代码如下:

class Solution {
public:
    bool oneEditAway(string first, string second) {
        if(first == second) return true;
        int n1 = first.size(), n2 = second.size();
        if(abs(n1 - n2) > 1) return false;
        int count = 0;
        int i = 0, j = 0;
        while(i < n1 && j < n2) {
            if(first[i] != second[j]) {
                if(n1 != n2) {
                    if(n1 > n2) i ++;
                    else j ++;
                } else {
                    i ++;
                    j ++;                   
                }
                count ++;
                if(count > 1) return false;
            } else {
                i ++;
                j ++;
            }
        }
        return true;
    }
};

简单优化一下即为:

class Solution {
public:
    bool oneEditAway(string first, string second) {
        if(first == second) return true;
        int n1 = first.size(), n2 = second.size();
        if(abs(n1 - n2) > 1) return false;
        int count = 0;
        int i = 0, j = 0;
        while(i < n1 && j < n2) {
            if(first[i] != second[j]) {
                if(n1 != n2) {
                    if(n1 > n2) j --;
                    else i --;
                } 
                count ++;
                if(count > 1) return false;
            } 
            i ++;
            j ++;
        }
        return true;
    }
};
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/878887.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号