From adbaeaddeecc4e9beafe83d4962a24c171641e08 Mon Sep 17 00:00:00 2001 From: Eat-Swap Date: Fri, 13 May 2022 23:19:17 +0800 Subject: [PATCH] add: 220513-CN [cpp] --- cpp/2205/220513-CN.cpp | 35 +++++++++++++++++++++++++++++++++++ cpp/2205/CMakeLists.txt | 2 +- 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 cpp/2205/220513-CN.cpp diff --git a/cpp/2205/220513-CN.cpp b/cpp/2205/220513-CN.cpp new file mode 100644 index 0000000..57fb313 --- /dev/null +++ b/cpp/2205/220513-CN.cpp @@ -0,0 +1,35 @@ +#include +#include + +/** + * 面试题 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; +} diff --git a/cpp/2205/CMakeLists.txt b/cpp/2205/CMakeLists.txt index 3342587..3a3353c 100644 --- a/cpp/2205/CMakeLists.txt +++ b/cpp/2205/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2205) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2205 220513.cpp) +ADD_EXECUTABLE(2205 220513-CN.cpp)