/*
字符串有三种编辑操作:插入一个字符、删除一个字符或者替换一个字符。 给定两个字符串,编写一个函数判定它们是否只需要一次(或者零次)编辑。
示例 1:
输入:
first = "pale"
second = "ple"
输出: True
示例 2:
输入:
first = "pales"
second = "pal"
输出: False
来源:力扣(LeetCode)
*/
/*
说明:
1、两个指针分别指向first和second;
2、遍历指针,遇到字符不等,长的字符串指针+1,短的不变,计数一次;
3、计算超过一次则失败,否则能走到最后就认为成功;
*/
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool oneEditAway(char* first, char* second) {
int len1, len2;
int modifyCnt = 0;
char *ptrFirst = first, *ptrSecond = second;
if (!first || !second){
return false;
}
len1 = strlen(first);
len2 = strlen(second);
if (len1 > len2 + 1 || len2 > len1 + 1) {
return false;
}
while (*ptrFirst!='\0' && *ptrSecond!='\0'){
if (*ptrFirst == *ptrSecond) {
ptrFirst++;
ptrSecond++;
continue;
}
if (modifyCnt > 0) {
return false;
}
modifyCnt++;
if (len1 > len2) {
ptrFirst++;
} else if(len1 < len2){
ptrSecond++;
} else {
ptrFirst++;
ptrSecond++;
}
}
return true;
}
int main(){
char first[128] = {0}, second[128] = {0};
while(1) {
printf("first:");
fgets(first, sizeof(first), stdin);
first[strlen(first)-1] = '\0';
printf("second:");
fgets(second, sizeof(second), stdin);
second[strlen(second)-1] = '\0';
printf("result:%d\r\n",oneEditAway(first, second));
}
}
一次编辑
最新推荐文章于 2022-05-13 10:24:16 发布