add: 220318 [cpp]

This commit is contained in:
Lam Haoyin 2022-03-19 01:41:50 +08:00
parent 4fcc7edb67
commit b8c6b0eab4
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 31 additions and 1 deletions

30
cpp/2203/220318.cpp Normal file
View File

@ -0,0 +1,30 @@
#include <string>
/**
* 316. Remove Duplicate Letters
* 1081. Smallest Subsequence of Distinct Characters
*
* Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.
*/
class Solution {
public:
static std::string removeDuplicateLetters(const std::string& s) {
int lastViewed[26]{}, n = s.length();
for (int i = 0; i < n; ++i)
lastViewed[s[i] - 'a'] = i;
char ans[30]{};
bool used[26]{};
int top = -1;
for (int i = 0; i < n; ++i) {
if (!used[s[i] - 'a']) {
while (top >= 0 && ans[top] > s[i] && lastViewed[ans[top] - 'a'] > i) {
used[ans[top] - 'a'] = false;
ans[top--] = 0;
}
used[(ans[++top] = s[i]) - 'a'] = true;
}
}
return ans;
}
};

View File

@ -3,4 +3,4 @@ PROJECT(2203)
SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2203 220317-CN.cpp)
ADD_EXECUTABLE(2203 220318.cpp)