代码(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]...
这样最后stack里面就是字符序的possible result 1publicclassSolution {2publicString removeDuplicateLetters(String s) {3if(s==null|| s.length()==0)return"";4Stack<Character> st =newStack<Character>();5StringBuffer sb =newStringBuffer();6boolean[] visited =newboolean[26];7int[] count =newin...
其中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.s...
我们一位一位处理字符串,假设处理到了第i位,并且已经得到当前最优的字符串s,如果第i位已经出现在s中,那么就没必要保留这一位了。 如果没有,考虑s的最后一个字母,如果它比最后第i位小,并且在第i位之后还出现了,那么就删掉,直到s为空或者s的最后一个字母不满足条件,把第i位放到最后。 举样例跑一遍: cbacd...
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://discuss.leetcode.com/topic/31404/a-short-o-n-recursive-greedy-solution * 贪心算法 * */ public class Solution { public String removeDuplicateLetters(String s) { if(s==null || s.length()<=0) return ""; else { int[] count=new int[26]; ...
3.代码示例 1classSolution 2{ 3public: 4stringremoveDuplicateLetters(strings) 5{ 6intn=s.size(); 7vector<int>c(26,0),in(26,0); 8for(inti=0;i<n;i++) ++c[s[i]-'a']; 9stringans; 10for(inti=0;i<n;i++) 11{ 12--c[s[i...
316. Remove Duplicate Letters 去除重复字母 给你一个字符串s,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证返回结果的字典序最小(要求不能打乱其他字符的相对位置)。 注意:该题与 1081https://leetcode-cn.com/problems/smallest-subsequence-of-distinct-characters相同...
classSolution{publicStringremoveDuplicateLetters(String s){StringBuilder sb=newStringBuilder();int[]count=newint[26];boolean[]used=newboolean[26];char[]chs=s.toCharArray();for(char c:chs){count[c-'a']++;}for(char c:chs){count[c-'a']--;if(used[c-'a'])continue;while(sb.length()>...
Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique. Example 1: Input:"abbaca"Output:"ca"Explanation:For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. ...