作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/remove-duplicate-letters/

题目描述

Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.

Example 1:

Input: "bcabc"
Output: "abc"

Example 2:

Input: "cbacdcbc"
Output: "acdb"

题目大意

从一组字符串中取字符,使得生成结果中每个字符必须出现一次而且只出现一次,并且要求所得结果是字符串顺序最小的。

解题方法

这个题的难点在于使得结果是字符串顺序最小。解题思路也是围绕这个展开。

先顺一下思路,首先,每个字符都必须要出现一次,那么当这个字符只有一次机会的时候,必须添加到结果字符串结尾中去,反之,如果这个字符的次数没有降为0,即后面还有机会,那么可以先把优先级高的放进来,把这个字符放到后面再处理。所以,我们可以使用一个栈,有点类似单调递增栈的意思,但其实并不是单调栈。我们的思路就是把还可以放到后面的字符弹出栈,留着以后处理,字符序小的插入到对应的位置。

首先,为了知道每个字符出现了多少次,必须做一次次数统计,这个步骤大家都是知道的。

然后,需要借助一个栈来实现字符串构造的操作。具体操作如下:

从输入字符串中逐个读取字符c,并把c的字符统计减一。

  1. 如果当前字符c已经在栈里面出现,那么跳过。
  2. 如果当前字符c在栈里面,那么:
    1. 如果当前字符c小于栈顶,并且栈顶元素有剩余(后面还能再添加进来),则出栈栈顶,标记栈顶不在栈中。重复该操作直到栈顶元素不满足条件或者栈为空。
    2. 入栈字符c,并且标记c已经在栈中。

python代码如下:

class Solution(object):
def removeDuplicateLetters(self, s):
"""
:type s: str
:rtype: str
"""
count = collections.Counter(s)
stack = []
visited = collections.defaultdict(bool)
for c in s:
count[c] -= 1
if visited[c]:
continue
while stack and count[stack[-1]] and stack[-1] > c:
visited[stack[-1]] = False
stack.pop()
visited[c] = True
stack.append(c)
return "".join(stack)

C++代码如下:

class Solution {
public:
string removeDuplicateLetters(string s) {
unordered_map<char, bool> visited;
unordered_map<char, int> counter;
string res = "";
for (char c : s) ++counter[c];
for (char c : s) {
--counter[c];
if (visited[c]) {
continue;
}
while (!res.empty() && counter[res.back()] && c < res.back()) {
visited[res.back()] = false;
res.pop_back();
}
res += c;
visited[c] = true;
}
return res;
}
};

参考资料:

https://www.jiuzhang.com/solution/remove-duplicate-letters/
https://www.jianshu.com/p/8d75723657ad
https://blog.csdn.net/u012050154/article/details/51604942
http://www.cnblogs.com/grandyang/p/5085379.html

日期

2019 年 1 月 8 日 —— 别熬夜,我都开始有黑眼圈了。。

【LeetCode】316. Remove Duplicate Letters 解题报告(Python & C++)的更多相关文章

  1. [LeetCode] 316. Remove Duplicate Letters 移除重复字母

    Given a string which contains only lowercase letters, remove duplicate letters so that every letter ...

  2. leetcode@ [316] Remove Duplicate Letters (Stack & Greedy)

    https://leetcode.com/problems/remove-duplicate-letters/ Given a string which contains only lowercase ...

  3. leetcode 316. Remove Duplicate Letters

    Given a string which contains only lowercase letters, remove duplicate letters so that every letter ...

  4. 【LeetCode】848. Shifting Letters 解题报告(Python)

    [LeetCode]848. Shifting Letters 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http ...

  5. 贪心:leetcode 870. Advantage Shuffle、134. Gas Station、452. Minimum Number of Arrows to Burst Balloons、316. Remove Duplicate Letters

    870. Advantage Shuffle 思路:A数组的最大值大于B的最大值,就拿这个A跟B比较:如果不大于,就拿最小值跟B比较 A可以改变顺序,但B的顺序不能改变,只能通过容器来获得由大到小的顺 ...

  6. 【leetcode】316. Remove Duplicate Letters

    题目如下: Given a string which contains only lowercase letters, remove duplicate letters so that every l ...

  7. 316. Remove Duplicate Letters

    Given a string which contains only lowercase letters, remove duplicate letters so that every letter ...

  8. 316. Remove Duplicate Letters (accumulate -> count of the difference elements in a vector)

    Given a string which contains only lowercase letters, remove duplicate letters so that every letter ...

  9. LeetCode 917 Reverse Only Letters 解题报告

    题目要求 Given a string S, return the "reversed" string where all characters that are not a le ...

随机推荐

  1. fatal error: runtime: out of memory

    [root@VM_0_10_centos frp_0.27.0_linux_amd64]# top top - 21:09:19 up 2 days, 4 min, 2 users, load ave ...

  2. web性能测试工具——http_load

    http_load是一款基于Linux平台的web服务器性能测试工具,用于测试web服务器的吞吐量与负载,web页面的性能. http_load是基于linux.unix平台的一种性能测工具 它以并行 ...

  3. Go知识点大纲

    目录 1. 基本介绍 2. 安装及配置 3. 变量 4. 常量 5. 数据类型 5.1 numeric(数字) 5.2 string(字符串) 5.3 array(数组) 5.4 slice(切片) ...

  4. Dango之form校验组件

    目录 1.引入案例 2. form组件的功能 3. form组件的使用 3.1 自定义form校验类 3.2 校验数据 3.3 渲染页面 3.4 展示错误信息 3.5 自定义校验结果 3.6 form ...

  5. Python压缩&解压缩

    Python中常用的压缩模块有zipfile.tarfile.gzip 1.zipfile模块的简单使用 import zipfile # 压缩 z1 = zipfile.ZipFile('zip_t ...

  6. 27-Roman to Integer-Leetcode

    Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 t ...

  7. Java 读取TXT文件的多种方式

    1).按行读取TXT文件package zc;import java.io.BufferedReader;import java.io.File;import java.io.FileNotFound ...

  8. 关于JSONObject的性能问题

    现有一段代码: private JSONObject override(User user, UserVO vo) { String json = JSON.toJSONString(vo); JSO ...

  9. 学习java的第十四天

    一.今日收获 1.完成了手册第二章没有验证完成的例题 2.预习了第三章的算法以及for语句与if语句的用法 二.今日难题 1.验证上出现问题,没有那么仔细. 2.第二章还有没有完全理解的问题 三.明日 ...

  10. 从源码看RequestMappingHandlerMapping的注册与发现

    1.问题的产生 日常开发中,大多数的API层中@Controller注解和@RequestMapping注解都会被使用在其中,但是为什么标注了@Controller和@RequestMapping注解 ...