Remove Duplicate Letters

Posted keepshuatishuati

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Remove Duplicate Letters相关的知识,希望对你有一定的参考价值。

 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的主要内容,如果未能解决你的问题,请参考以下文章

***Leetcode 316. Remove Duplicate Letters

316. Remove Duplicate Letters

316. Remove Duplicate Letters

316. Remove Duplicate Letters

leetcode 316. Remove Duplicate Letters

LeetCode "Remove Duplicate Letters" !!