首页 > 代码库 > 316. Remove Duplicate Letters
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"
The runtime is O(26 * n) = O(n).
public class Solution { // 形成字典 int[26] //找到当前str中最小的值 或者为 cnt为1的char //recursive: remove min 前面所有的char 然后将s中所有的charAt(min) 的字符移除; public String removeDuplicateLetters(String s) { int[] count = new int[26]; int min = 0; for(int i = 0 ; i < s.length() ; i++){ count[s.charAt(i) - ‘a‘] ++; } for(int i = 0 ; i < s.length(); i++){ if(s.charAt(i) < s.charAt(min)) min = i; if(--count[s.charAt(i) - ‘a‘] == 0) break; } return s.length()==0 ? "" : s.charAt(min) + removeDuplicateLetters(s.substring(min+1).replaceAll(""+s.charAt(min), "")); } }
316. Remove Duplicate Letters
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。