Remove Duplicate Letters
发布日期:2021-09-06 22:32:30 浏览次数:6 分类:技术文章

本文共 1177 字,大约阅读时间需要 3 分钟。

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.

转载于:https://www.cnblogs.com/shuashuashua/p/5642240.html

转载地址:https://blog.csdn.net/weixin_34273481/article/details/93295742 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:面对众多的前端框架,你该如何学习?
下一篇:hdu 6243,6247

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年04月18日 11时32分43秒