Código fuente para todos los temas: dirección de Git
tema
给你一个字符串 s ,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证 返回结果的字典序最小(要求不能打乱其他字符的相对位置)。
注意:该题与 1081 https://leetcode-cn.com/problems/smallest-subsequence-of-distinct-characters 相同
示例 1:
输入:s = "bcabc"
输出:"abc"
示例 2:
输入:s = "cbacdcbc"
输出:"acdb"
提示:
1 <= s.length <= 104
s 由小写英文字母组成
1081题表述如下:
返回 s 字典序最小的子序列,该子序列包含 s 的所有不同字符,且只包含一次。
Programa:
class Solution
{
public:
string removeDuplicateLetters(string s)
{
int len = s.size();
vector<int> hash(26, 0);
vector<int> used(26, 0);
vector<char> sta(26, 96);
int index = 0;
for (int i = 0; i < len; i++)
{
hash[s[i] - 'a']++;
}
sta[0] = s[0];
hash[s[0] - 'a']--;
used[s[0] - 'a']++;
for (int i = 1; i < len; i++)
{
while (index >= 0 && sta[index] > s[i] && hash[sta[index] - 'a'] > 0 && used[s[i] - 'a'] == 0)
{
used[sta[index] - 'a'] = 0;
index--;
}
if (used[s[i] - 'a'] == 0)
{
sta[++index] = s[i];
used[s[i] - 'a'] = 1;
}
hash[s[i] - 'a']--;
}
string res;
res.assign(sta.begin(), sta.begin() + index + 1);
return res;
}
};
Cálculo de complejidad
- Complejidad del tiempo: O (n)
- Complejidad espacial: O (n)