/**
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"
*/
import java.util.*;
public class RemoveDuplicateLetters{
public static String removeDups(String s){
int[] res = new int[26];
boolean[] visited = new boolean[26];
char[] chars = s.toCharArray();
for(char c:chars){
res[c-'a']++;
}
Stack<Character> st = new Stack<Character>();
int index = 0;
for(char c:chars){
index = c-'a';
res[index]--;
//if character already in stack, no worries
if(visited[index]){
continue;
}
//if the current character is smaller than top of stack and the top of stack
//is available in remaining portion of string, we can remove the top of stack
while(!st.isEmpty() && c<st.peek() && res[st.peek()-'a']>0){
visited[st.pop()-'a'] = false;
}
st.push(c);
visited[index] = true;
}
//build string from the stack in reverse order
StringBuilder sb = new StringBuilder();
while(!st.isEmpty()){
sb.insert(0, st.pop());
}
return sb.toString();
}
public static void main(String args[]){
System.out.println(removeDups("bcabc"));
System.out.println(removeDups("cbacdcbc"));
}
}
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"
*/
import java.util.*;
public class RemoveDuplicateLetters{
public static String removeDups(String s){
int[] res = new int[26];
boolean[] visited = new boolean[26];
char[] chars = s.toCharArray();
for(char c:chars){
res[c-'a']++;
}
Stack<Character> st = new Stack<Character>();
int index = 0;
for(char c:chars){
index = c-'a';
res[index]--;
//if character already in stack, no worries
if(visited[index]){
continue;
}
//if the current character is smaller than top of stack and the top of stack
//is available in remaining portion of string, we can remove the top of stack
while(!st.isEmpty() && c<st.peek() && res[st.peek()-'a']>0){
visited[st.pop()-'a'] = false;
}
st.push(c);
visited[index] = true;
}
//build string from the stack in reverse order
StringBuilder sb = new StringBuilder();
while(!st.isEmpty()){
sb.insert(0, st.pop());
}
return sb.toString();
}
public static void main(String args[]){
System.out.println(removeDups("bcabc"));
System.out.println(removeDups("cbacdcbc"));
}
}
No comments:
Post a Comment