Remove Duplicate Letters I
Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once.
Example:
Given "bcabc"
Return "abc"
Given "cbacdcbc"
Return "abcd"
1 public class Solution { 2 public String removeDuplicateLetters(String s) { 3 if (s == null || s.length() <= 1) 4 return s; 5 6 int res = 0; 7 for (int i = 0; i < s.length(); i++) { 8 res = res | (1 << s.charAt(i) - ‘a‘); 9 } 10 11 StringBuilder sb = new StringBuilder(); 12 int k = 1; 13 for (int i = 0; i < 32; i++) { 14 if ((res & (k << i)) != 0) { 15 sb.append((char) (‘a‘ + i)); 16 } 17 } 18 return sb.toString(); 19 } 20 }
Remove Duplicate Letters II
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"
分析:https://segmentfault.com/a/1190000004188227
这道题要保证顺序要一致,而且还是最小的。
读字符的过程中,把字符存到stack里,当发现stack之前存的字符中比当前字符大而且频率还大于0就可以把那个字符pop出去。类似这种题目都可以用stack解决。基本思想就是在一定的限制条件下pop出比当前选择差的元素。
1 public class Solution { 2 public String removeDuplicateLetters(String s) { 3 int[] freqs = new int[256]; 4 5 // 统计字符频率 6 for (int i = 0; i < s.length(); i++) { 7 freqs[s.charAt(i)]++; 8 } 9 10 boolean[] visited = new boolean[256]; // 用来标记存在stack里的字符 11 Deque<Character> q = new ArrayDeque<>(); 12 13 for (int i = 0; i < s.length(); i++) { 14 char c = s.charAt(i); 15 freqs[c]--; 16 if (visited[c]) continue; 17 18 // pop出stack当中比当前字符大但后面还存在的的字符, 19 while (!q.isEmpty() && q.peek() > c && freqs[q.peek()] > 0) { 20 visited[q.pop()] = false; 21 } 22 q.push(c); 23 visited[c] = true; 24 } 25 26 StringBuilder sb = new StringBuilder(); 27 for (char c : q) { 28 sb.append(c); 29 } 30 31 return sb.reverse().toString(); 32 } 33 }
时间: 2024-10-12 13:48:22