add: 220513-CN [cpp]

This commit is contained in:
Eat-Swap 2022-05-13 23:19:17 +08:00
parent 523d79e94a
commit adbaeaddee
Signed by: Eatswap
GPG Key ID: BE661106A1F3FA0B
2 changed files with 36 additions and 1 deletions

35
cpp/2205/220513-CN.cpp Normal file
View File

@ -0,0 +1,35 @@
#include <string>
#include <cstdio>
/**
* 01.05. One Away LCCI
* There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away.
*/
class Solution {
public:
static bool oneEditAway(const std::string& first, const std::string& second) {
int ps = 0, pt = 0, mod = 0, ls = first.length(), lt = second.length();
if (std::abs(ls - lt) > 1)
return false;
const char* s = first.c_str(), * t = second.c_str();
for (; ps < ls && pt < lt; ++ps, ++pt) {
if (s[ps] == t[pt])
continue;
if (mod++)
return false;
if (pt + 1 < lt && s[ps] == t[pt + 1])
++pt;
else if (ps + 1 < ls && s[ps + 1] == t[pt])
++ps;
// else ++ps, ++pt;
}
return ((ps == ls) && (pt == lt)) || (!mod && std::abs(ls - lt) <= 1);
}
};
int main() {
std::printf("%s\n", Solution::oneEditAway("", "a") ? "true" : "false");
return 0;
}

View File

@ -3,4 +3,4 @@ PROJECT(2205)
SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2205 220513.cpp)
ADD_EXECUTABLE(2205 220513-CN.cpp)