Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.60 KB | None | 0 0
  1. public static String removeDuplicateLetters(String s) {
  2. if (s.length() == 0)
  3. return "";
  4.  
  5. int[] count = new int[26];
  6. int pos = 0; // 紀錄位置
  7.  
  8. for (char c : s.toCharArray()) {
  9. count[c - 'a'] += 1;
  10. }
  11.  
  12. // 找到最小的字串
  13. for (int i = 0; i < s.length(); i++) {
  14. if (s.charAt(i) < s.charAt(pos)) {
  15. pos = i;
  16. }
  17. // 0的話表示字母最小是a
  18. if (--count[s.charAt(i) - 'a'] == 0)
  19. break;
  20. }
  21.  
  22. //求出每一個最小的位置並把它們加總
  23. String last = removeDuplicateLetters(s.substring(pos + 1).replaceAll("" + s.charAt(pos), ""));
  24. return s.charAt(pos) + last;
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement