[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 among all possible results.
Example:
Given "bcabc"
Return "abc"
Given "cbacdcbc"
Return "acdb"
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
给定一个只含有小写字母的字符串,移除重复的字符,每种字符只出现1次,返回字符串是按字典顺序中最小的组合。
解法:贪心算法Greedy,用1个HashMap或者数组统计出现的字符。然后再遍历一遍数组, 假设position = 0,每次找到字符比position的小就更新position,同时也更新count,当count[i] == 0的时候,这个字符就是我们要找的结果字符串里的第一个字符。之后因为其他字符的count还都 > 1,继续在s.substring(position + 1)的子串里递归查找第二个字符,注意要在这个子串里把第一个字符清除掉。
Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | public class Solution { public String removeDuplicateLetters(String s) { if (s == null || s.length() == 0 ) { return s; } int [] count = new int [ 26 ]; char [] res = new char [ 26 ]; int len = s.length(); for ( int i = 0 ; i < s.length(); i++) { count[s.charAt(i) - 'a' ]++; } int pos = 0 ; for ( int i = 0 ; i < len; i++) { if (s.charAt(i) < s.charAt(pos)) { pos = i; } count[s.charAt(i) - 'a' ]--; if (count[s.charAt(i) - 'a' ] == 0 ) { // found first minimum char break ; } } String charToRemove = String.valueOf(s.charAt(pos)); return charToRemove + removeDuplicateLetters(s.substring(pos + 1 ).replaceAll(charToRemove, "" )); } } |
Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class Solution( object ): def removeDuplicateLetters( self , s): """ :type s: str :rtype: str """ remaining = collections.defaultdict( int ) for c in s: remaining[c] + = 1 in_stack, stk = set (), [] for c in s: if c not in in_stack: while stk and stk[ - 1 ] > c and remaining[stk[ - 1 ]]: in_stack.remove(stk.pop()) stk + = c in_stack.add(c) remaining[c] - = 1 return "".join(stk) |
C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class Solution { public : string removeDuplicateLetters(string s) { int m[256] = {0}, visited[256] = {0}; string res = "0" ; for ( auto a : s) ++m[a]; for ( auto a : s) { --m[a]; if (visited[a]) continue ; while (a < res.back() && m[res.back()]) { visited[res.back()] = 0; res.pop_back(); } res += a; visited[a] = 1; } return res.substr(1); } }; |
All LeetCode Questions List 题目汇总
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架