add: 220419-CN [cpp]

This commit is contained in:
eat-swap 2022-04-19 15:55:06 +08:00
parent 6439a6aed0
commit 6bb36e7bb3
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 31 additions and 1 deletions

30
cpp/2204/220419-CN.cpp Normal file
View File

@ -0,0 +1,30 @@
#include <algorithm>
#include <string>
#include <vector>
/**
* 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<int> shortestToChar(const std::string& s, char c) {
int n = s.length();
std::vector<int> 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;
}
};

View File

@ -3,4 +3,4 @@ PROJECT(2204)
SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2204 220418.cpp)
ADD_EXECUTABLE(2204 220419-CN.cpp)