- 不同字符的最小子序列
返回字符串 text 中按字典序排列最小的子序列,该子序列包含 text 中所有不同字符一次。
示例 1:
输入:“cdadabcc”
输出:“adbc”
示例 2:
输入:“abcd”
输出:“abcd”
示例 3:
输入:“ecbacba”
输出:“eacb”
示例 4:
输入:“leetcode”
输出:“letcod”
提示:
1 <= text.length <= 1000
text 由小写英文字母组成
char * smallestSubsequence(char * text){
int flag[26];
memset(flag, 0, sizeof(flag));
char * p = text;
char * res = (char *)malloc(27);
memset(res, 0, 27);
int index = 0;
while ('\0' != *p) {
int ch = *p - 'a';
if (flag[ch] == 1) {
p++;
continue;
}
while (index != 0 && *p < res[index-1] && strchr(p, res[index-1]) != NULL) {
flag[res[index-1]-'a']--;
index--;
}
flag[ch]++;
res[index++] = *p++;
}
res[index] = '\0';
return res;
}
/*0ms,5.4MB*/