add: 220509-CN [cpp]

This commit is contained in:
Eat-Swap 2022-05-09 23:31:10 +08:00
parent 257eded1cc
commit 6609853252
Signed by: Eatswap
GPG Key ID: BE661106A1F3FA0B
2 changed files with 36 additions and 1 deletions

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

@ -0,0 +1,35 @@
#include <vector>
#include <string>
#include <iostream>
/**
* 942. DI String MatchA permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where:
*
* s[i] == 'I' if perm[i] < perm[i + 1], and
* s[i] == 'D' if perm[i] > perm[i + 1].
* Given a string s, reconstruct the permutation perm and return it. If there are multiple valid permutations perm, return any of them.
*
*/
class Solution {
public:
static std::vector<int> diStringMatch(const std::string& s) {
int p = 1, n = -1;
std::vector<int> ret;
ret.reserve(s.length() + 1);
ret.push_back(0);
for (char c : s)
ret.push_back(c == 'I' ? p++ : n--);
n = (-n) - 1;
for (int& i : ret)
i += n;
return ret;
}
};
int main() {
auto r = Solution::diStringMatch("DDI");
for (const auto& i : r)
std::cout << i << ' ';
return 0;
}

View File

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