1 public class Solution {
 2     public String removeDuplicateLetters(String s) {
 3         if (s.length() < 2) {
 4             return s;
 5         }
 6         int[] letters = new int[26];
 7         for (char c : s.toCharArray()) {
 8             letters[c - 'a']++;
 9         }
10         boolean[] visited = new boolean[26];
11         StringBuilder result = new StringBuilder(" ");
12         for (char c : s.toCharArray()) {
13             letters[c - 'a']--;
14             if (visited[c - 'a']) {
15                 continue;
16             }
17             visited[c - 'a'] = true;
18             while (c < result.charAt(result.length() - 1) && letters[result.charAt(result.length() - 1) - 'a'] > 0) {
19                 visited[result.charAt(result.length() - 1) - 'a'] = false;
20                 result.setLength(result.length() - 1);
21             }
22             result.append(c);
23         }
24         return result.toString().substring(1);
25     }
26 }

1. Add " " to ensure the comparision works. Or add a condition that result.length() > 0

2. character counting decrease happens before check it has been visited or not.

posted on 2016-07-05 07:13  keepshuatishuati  阅读(107)  评论(0编辑  收藏  举报