From 6bb36e7bb387e7c3d5f831ac8f9af89cc0f61314 Mon Sep 17 00:00:00 2001 From: eat-swap Date: Tue, 19 Apr 2022 15:55:06 +0800 Subject: [PATCH] add: 220419-CN [cpp] --- cpp/2204/220419-CN.cpp | 30 ++++++++++++++++++++++++++++++ cpp/2204/CMakeLists.txt | 2 +- 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 cpp/2204/220419-CN.cpp diff --git a/cpp/2204/220419-CN.cpp b/cpp/2204/220419-CN.cpp new file mode 100644 index 0000000..61d969d --- /dev/null +++ b/cpp/2204/220419-CN.cpp @@ -0,0 +1,30 @@ +#include +#include +#include + +/** + * 821. Shortest Distance to a Character + * Given a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest occurrence of character c in s. + * The distance between two indices i and j is abs(i - j), where abs is the absolute value function. + */ + +class Solution { +public: + static std::vector shortestToChar(const std::string& s, char c) { + int n = s.length(); + std::vector ret(n, 0x7FFFFFFF); + for (int prev = -1, i = 0; i < n; ++i) { + if (s[i] == c) + prev = i; + if (prev != -1) + ret[i] = std::min(ret[i], std::abs(prev - i)); + } + for (int prev = -1, i = n - 1; i >= 0; --i) { + if (s[i] == c) + prev = i; + if (prev != -1) + ret[i] = std::min(ret[i], std::abs(prev - i)); + } + return ret; + } +}; diff --git a/cpp/2204/CMakeLists.txt b/cpp/2204/CMakeLists.txt index 82d1ed7..df590e0 100644 --- a/cpp/2204/CMakeLists.txt +++ b/cpp/2204/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2204) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2204 220418.cpp) +ADD_EXECUTABLE(2204 220419-CN.cpp)