Skip to content

Instantly share code, notes, and snippets.

@DracoLi
Created April 6, 2012 15:37
Show Gist options
  • Save DracoLi/2320871 to your computer and use it in GitHub Desktop.
Save DracoLi/2320871 to your computer and use it in GitHub Desktop.
A algorithm questions I couldn't solve
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Scanner;
public class beauty {
public static String solve(String input) {
int n = input.length();
ArrayList<Character> r = new ArrayList<Character>();
char prevc = 'a';
for (int i = 0; i < n; i++) {
char c = input.charAt(i);
if (!r.contains(c)) {
r.add(c);
prevc = c;
}else {
// Determine if we keep this char or not
int lastIndex = r.indexOf(c);
if (lastIndex + 1 < r.size() && c < r.get(lastIndex+1)) {
// Remove previous one
r.remove(lastIndex);
r.add(c);
prevc = c;
}
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < r.size(); i++) {
sb.append(r.get(i));
}
return sb.toString();
}
public static void main(String[] args) {
Scanner c = null;
try {
c = new Scanner(System.in);
}catch(Exception e) {
System.out.println(e.getMessage());
}
String str = c.nextLine();
System.out.println(solve(str));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment