代码(Python3) class Solution: def removeDuplicateLetters(self, s: str) -> str: # last_index[ch] 表示 ch 在 s 中的最后一个出现的位置 last_index: Dict[str, int] = { # 带下标遍历 s 中的字符,更新每个字符最后一次出现的位置 ch: i for i, ch in enumerate(s) } # is_in_stack[ch]...
题目地址:https://leetcode.com/problems/remove-duplicate-letters/ 题目描述 Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results...
我们一位一位处理字符串,假设处理到了第i位,并且已经得到当前最优的字符串s,如果第i位已经出现在s中,那么就没必要保留这一位了。 如果没有,考虑s的最后一个字母,如果它比最后第i位小,并且在第i位之后还出现了,那么就删掉,直到s为空或者s的最后一个字母不满足条件,把第i位放到最后。 举样例跑一遍: cbacd...
leetcode:316. Remove Duplicate Letters 题解 题目Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical orde......
LeetCode 316. Remove Duplicate Letters(贪心) 题目 题意:删除重复的字符,得到字典序最小的结果字符串 题解:贪心,咱们从结果字符串的左边开始,左边第一个字符在原字符串中的右边一定有n-1个不同的字符,这里n就是结果字符串的长度。 所以我们每次遍历数组,找到右边有n-1个不同字符的字符,并选择最小的那个。
其中remove函数需要使用algorithm库文件。算法复杂度为O(26 * n) = O(n) 1classSolution {2public:3stringremoveDuplicateLetters(strings) {4vector<int> alp(26, -1);5for(inti =0, n = s.size(); i < n; i++)6alp[(int)(s[i] -'a')] =i;7intpos = -1;8for(inti =0, n = s....
177 -- 23:27 App Leetcode 307 Range Sum Query - Mutable | 分块算法解析 199 -- 33:21 App Leetcode 315 Count of Smaller Numbers After Self | 树状数组 164 -- 22:30 App Leetcode 302 Smallest Rectangle Enclosing Black Pixels | 二分算法 278 -- 5:15 App Leetcode 311 Sparse Matrix...
详见:https://leetcode.com/problems/remove-duplicate-letters/description/ C++: class Solution { public: string removeDuplicateLetters(string s) { int m[256]={0},visited[256]={0}; string res="0"; for(char a:s) { ++m[a]; }
leetcode 316. Remove Duplicate Letters Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order a......
Leetcode: Remove Duplicate Letters Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results....