标签:
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.
标签:
原文地址:http://www.cnblogs.com/shuashuashua/p/5642240.html