【LeetCode】791. Custom Sort String 解题报告(Python & C++)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/custom-sort-string/description/
题目描述
S and T are strings composed of lowercase letters. In S, no letter occurs more than once.
S was sorted in some custom order previously. We want to permute the characters of T so that they match the order that S was sorted. More specifically, if x occurs before y in S, then x should occur before y in the returned string.
Return any permutation of T (as a string) that satisfies this property.
Example :
Input:
S = "cba"
T = "abcd"
Output: "cbad"
Explanation:
"a", "b", "c" appear in S, so the order of "a", "b", "c" should be "c", "b", and "a".
Since "d" does not appear in S, it can be at any position in T. "dcba", "cdba", "cbda" are also valid outputs.
Note:
- S has length at most 26, and no character is repeated in S.
- T has length at most 200.
- S and T consist of lowercase letters only.
题目大意
S是一个自定义的字母表顺序,现在要把T中的字符按照S的顺序进行排序。如果T中有S中不存在的字符,那么可以处在结果的任何位置。
解题方法
按顺序构造字符串
使用字典保存T中的每个字母出现的次数,然后遍历S中的每个字符,查表构建新的结果字符串,并且把已经遍历了的字符的次数设为0。最后把count中剩余的字符放到最后。
这里用到了一个技巧,Counter中使用不存在的索引会返回0.
如:
from collections import Counter
count = Counter("Hello World!")
print count['8']
##输出0
代码:
from collections import Counter
class Solution(object):
def customSortString(self, S, T):
"""
:type S: str
:type T: str
:rtype: str
"""
count = Counter(T)
answer = ''
for s in S:
answer += s * count[s]
count[s] = 0
for c in count:
answer += c * count[c]
return answer
C++代码如下:
d.count只会返回0或者1,想要得到次数使用d[c],但是这个在不存在的情况下会新增key=c。最好使用find()返回的是迭代器。
class Solution {
public:
string customSortString(string S, string T) {
map<char, int> d;
for (char c : T) d[c]++;
string res;
for (char c : S) {
for (int i = 0; i < d[c]; i++) {
res += c;
}
d[c] = 0;
}
for (auto k : d) {
if (k.second) {
for (int i = 0; i < k.second; i++) {
res += k.first;
}
}
}
return res;
}
};
学习到C++的string有构造方法以下构造方法:
(6) fill constructor
string (size_t n, char c);
Fills the string with n consecutive copies of character c.
注意第一个位置是字符重复次数,第二个参数是字符。代码如下:
class Solution {
public:
string customSortString(string S, string T) {
map<char, int> d;
for (char c : T) d[c]++;
string res = "";
for (char c : S) {
res += string(d[c], c);
d[c] = 0;
}
for (auto k : d) {
res += string(k.second, k.first);
}
return res;
}
};
排序
这个题目里面说了,在S中没有出现的字符可以出现在任意位置,所以这个题本质上上也是一个排序问题。对于排序问题,我们就必须明白,按照什么排序。在string中默认的排序方式是ASCII,但是这个题相当于给了我们一个新的排序方法:按照在S出现的位置排序。
所以,使用字典保存S中字符出现的每个位置索引,然后对T进行排序,排序的key就是该字符在S中的位置索引。由于使用的字典是defaultdict,因此如果T中的字符在S中没有出现,那么位置会是0,这个无所谓了,题目不关心。
python代码如下:
class Solution(object):
def customSortString(self, S, T):
"""
:type S: str
:type T: str
:rtype: str
"""
pos = collections.defaultdict(int)
for i in range(len(S)):
pos[S[i]] = i
res = sorted(T, key = lambda x : pos[x])
return "".join(res)
日期
2018 年 2 月 26 日
2018 年 12 月 4 日 —— 周二啦!
2019 年 1 月 6 日 —— 打球打的腰酸背痛
【LeetCode】791. Custom Sort String 解题报告(Python & C++)的更多相关文章
- LeetCode 791. Custom Sort String
题目链接:https://leetcode.com/problems/custom-sort-string/description/ S and T are strings composed of l ...
- [leetcode]791. Custom Sort String自定义排序字符串
S and T are strings composed of lowercase letters. In S, no letter occurs more than once. S was sort ...
- 【LeetCode】481. Magical String 解题报告(Python)
[LeetCode]481. Magical String 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http:/ ...
- 791. Custom Sort String - LeetCode
Question 791. Custom Sort String Solution 题目大意:给你字符的顺序,让你排序另一个字符串. 思路: 输入参数如下: S = "cba" T ...
- 【LeetCode】87. Scramble String 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 动态规划 日期 题目地址:https://le ...
- 【LeetCode】796. Rotate String 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...
- 【LeetCode】148. Sort List 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...
- 【LeetCode】767. Reorganize String 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.me/ 题目地址:https://leetcode.com/problems/reorganiz ...
- 【LeetCode】344. Reverse String 解题报告(Java & Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 新构建字符串 原地翻转 日期 题目地址:https://lee ...
随机推荐
- 使用input+datalist简单实现实时匹配的可编辑下拉列表-并解决选定后浏览器默认只显示value的可读性问题
问题背景 最近小伙伴提了一个希望提高后台下拉列表可操作性的需求,原因是下拉列表选项过多,每次下拉选择比较费时费力且容易出错,硬着头皮啃了啃前端知识,网上搜寻了一些下拉列表实现的资料,这里总结一下. P ...
- fastjson转换数字时,格式化小数点
使用fastjson类库转换java对象时,对于BigDecimal类型,有时需要特殊格式,比如: 1.0,转为json时候,要求显式为1,因此需要在转换时做处理.步骤如下: 1.新建类,实现Valu ...
- 利用Lombok编写优雅的spring依赖注入代码,去掉繁人的@Autowired
大家平时使用spring依赖注入,都是怎么写的? @Servicepublic class OrderService {@Autowiredprivate UserService userServic ...
- d3入门二-常用 方法
CSV 版本6.5.0 这里的data实际上是csv中的一行数据 d3.csv("static/data/dept_cpu.csv",function (data) { conso ...
- vue2 安装打包部署
vue2项目搭建记录 mkdir -p /opt/wks/online_pre/1006cd /opt/wks/online_pre/1006mkdir hongyun-ui /opt/code/vu ...
- 【编程思想】【设计模式】【创建模式creational】lazy_evaluation
Python版 https://github.com/faif/python-patterns/blob/master/creational/lazy_evaluation.py #!/usr/bin ...
- 【Java 8】Predicate详解
一.java.util.function.Predicate 这里类是java自带主要广泛用在支持lambda表达式的API中. 1.接口源码 @FunctionalInterface public ...
- SpringBoot环境下java实现文件的下载
思路:文件下载,就是给服务器上的文件创建输入流,客户端创建输出流,将文件读出,读入到客户端的输出流中,(流与流的转换) package com.cst.icode.controller; import ...
- minkube在deban10上的安装步骤
环境准备: 所用机器为4c 16g i3 4170 1t机械硬盘 系统 debian 10 安装docker 如果已经安装并配置好可直接跳过 安装ssl sudo apt-get install ...
- 🔥🔥🔥Flutter 字节跳动穿山甲广告插件发布 - FlutterAds
前言 Flutter 已成为目前最流行的跨平台框架之一,在近期的几个大版本的发布中都提到了 Flutter 版本 Google 广告插件 [google_mobile_ads] .对于"出海 ...