Remove Duplicate Letters I & II

时间:2023-03-09 04:31:25
Remove Duplicate Letters I & II

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"

 public class Solution {
public String removeDuplicateLetters(String s) {
if (s == null || s.length() <= )
return s; int res = ;
for (int i = ; i < s.length(); i++) {
res = res | ( << s.charAt(i) - 'a');
} StringBuilder sb = new StringBuilder();
int k = ;
for (int i = ; i < ; i++) {
if ((res & (k << i)) != ) {
sb.append((char) ('a' + i));
}
}
return sb.toString();
}
}

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之前存的字符中比当前字符大 (这是一个很好的思路,如果当前字符或者数字需要与前面的字符或者数字比较,并且比较结果和以前的状态不一样,可以考虑用stack。)而且频率还大于0就可以把那个字符pop出去。类似这种题目都可以用stack解决。基本思想就是在一定的限制条件下pop出比当前选择差的元素。

 public class Solution {
public String removeDuplicateLetters(String s) {
int[] freqs = new int[]; // 统计字符频率
for (int i = ; i < s.length(); i++) {
freqs[s.charAt(i)]++;
} boolean[] visited = new boolean[]; // 用来标记存在stack里的字符
Deque<Character> q = new ArrayDeque<>(); for (int i = ; i < s.length(); i++) {
char c = s.charAt(i);
freqs[c]--;
if (visited[c]) continue; // pop出stack当中比当前字符大但后面还存在的的字符,
while (!q.isEmpty() && q.peek() > c && freqs[q.peek()] > ) {
visited[q.pop()] = false;
}
q.push(c);
visited[c] = true;
} StringBuilder sb = new StringBuilder();
for (char c : q) {
sb.append(c);
} return sb.reverse().toString();
}
}