분류: 스택, 문자열 /
문제
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.
Example 1:
Input: s = "bcabc"
Output: "abc"
Example 2:
Input: s = "cbacdcbc"
Output: "acdb"
Constraints:
1 <= s.length <= 104
s
consists of lowercase English letters.
Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/
풀이
string removeDuplicateLetters(string s) {
int count[26] = {};
for(char c:s) count[c-'a']++;
string ans = "";
for(char c:s) {
count[c-'a']--;
if(ans.find(c) != -1) continue;
while(!ans.empty() && count[ans.back()-'a'] && ans.back() >= c)
ans.pop_back();
ans.push_back(c);
}
return ans;
}
'Problem Solving > LeetCode' 카테고리의 다른 글
[LeetCode - 238] Products of Array Discluding Self - C++ (0) | 2024.05.31 |
---|---|
[LeetCode - 271] encode and decode strings - C++ (0) | 2024.05.30 |
[LeetCode - 916] Decoded String at Index - C++ (0) | 2023.09.30 |
[LeetCode - 3] Longest Substring Without Repeating Characters - C++ (0) | 2023.09.24 |