Created
April 6, 2012 15:37
-
-
Save DracoLi/2320871 to your computer and use it in GitHub Desktop.
A algorithm questions I couldn't solve
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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