[LintCode/LeetCode] Remove Duplicate Letters
文章目录
Problem
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"
Solution
public class Solution {
/**
* @param s: a string
* @return: return a string
*/
public String removeDuplicateLetters(String s) {
// write your code here
int[] count = new int[26]; // char-'a'
char[] stack = new char[26]; // index
boolean[] inStack = new boolean[26]; // char-'a'
for (char ch: s.toCharArray()) count[ch-'a']++;
int index = 0;
for (char ch: s.toCharArray()) {
count[ch-'a']--;
if (!inStack[ch-'a']) {
//check the stack: if has larger element
while (index > 0 && stack[index-1] > ch && count[stack[index-1]-'a'] > 0) {
index--;
inStack[stack[index]-'a'] = false;
}
stack[index++] = ch;
inStack[ch-'a'] = true;
}
}
return new String(stack, 0, index);
}
}

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论