码迷,mamicode.com
首页 > 其他好文 > 详细

Remove Duplicate Letters

时间:2016-07-05 07:42:23      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

 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.

Remove Duplicate Letters

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/5642240.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!