首页 > 编程语言 >#yyds干货盘点# LeetCode程序员面试金典:一次编辑

#yyds干货盘点# LeetCode程序员面试金典:一次编辑

时间:2022-12-01 18:32:58浏览次数:38  
标签:yyds return 金典 second index2 false index1 LeetCode first

题目:

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

 

示例 1:

输入:

first = "pale"

second = "ple"

输出: True

 

示例 2:

输入:

first = "pales"

second = "pal"

输出: False

代码实现:

class Solution {
public boolean oneEditAway(String first, String second) {
int m = first.length(), n = second.length();
if (n - m == 1) {
return oneInsert(first, second);
} else if (m - n == 1) {
return oneInsert(second, first);
} else if (m == n) {
boolean foundDifference = false;
for (int i = 0; i < m; i++) {
if (first.charAt(i) != second.charAt(i)) {
if (!foundDifference) {
foundDifference = true;
} else {
return false;
}
}
}
return true;
} else {
return false;
}
}

public boolean oneInsert(String shorter, String longer) {
int length1 = shorter.length(), length2 = longer.length();
int index1 = 0, index2 = 0;
while (index1 < length1 && index2 < length2) {
if (shorter.charAt(index1) == longer.charAt(index2)) {
index1++;
}
index2++;
if (index2 - index1 > 1) {
return false;
}
}
return true;
}
}

标签:yyds,return,金典,second,index2,false,index1,LeetCode,first
From: https://blog.51cto.com/u_13321676/5903574

相关文章

  • leetcode两数之和
    /***Definitionforsingly-linkedlist.*structListNode{*intval;*ListNode*next;*ListNode(intx):val(x),next(NULL){}*};*/classSol......
  • leetcode二叉树遍历
    #include<stdio.h>#include<string.h>#include<iostream>#include<vector>#include<queue>structTreeNode{intval;TreeNode*left;TreeNode*right;......
  • leetcode倒转整数--snprintf性能不行
    #include<stdio.h>#include<string.h>#include<iostream>#include<limits>intreverse(intx){longsum=0;while(x){sum=sum*10+x%10;......
  • leetcode-搜索插入位置
    intsearchInsert(std::vector<int>&nums,inttarget){inti=0;intsize=nums.size();for(;i<size;i++){if(nums[i]>=target){......
  • 设计链表-LeetCode707 基础题
    LeetCode链接:https://leetcode.cn/problems/design-linked-list/题目:设计链表的实现。您可以选择使用单链表或双链表。单链表中的节点应该具有两个属性:val 和 next。val......
  • leetcode 15. 三数之和 js实现
    给你一个整数数组 nums ,判断是否存在三元组 [nums[i],nums[j],nums[k]] 满足 i!=j、i!=k 且 j!=k ,同时还满足 nums[i]+nums[j]+nums[k]==0 。请......
  • LeetCode刷题记录.Day29
    前K个高频元素classSolution{public://小顶堆classmycomparison{public:booloperator()(constpair<int,int>&lhs,constpair<int,......
  • leetcode-160-easy
    IntersectionofTwoLinkedListsGiventheheadsoftwosinglylinked-listsheadAandheadB,returnthenodeatwhichthetwolistsintersect.Ifthetwolinke......
  • leetcode-111-easy
    MinimumDepthofBinaryTreeGivenabinarytree,finditsminimumdepth.Theminimumdepthisthenumberofnodesalongtheshortestpathfromtherootnode......
  • 力扣 leetcode 162. 寻找峰值
    问题描述峰值元素是指其值严格大于左右相邻值的元素。给你一个整数数组nums,找到峰值元素并返回其索引。数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即......