【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 ...
随机推荐
- git添加新账号
1,在linux上添加账号 useradd test passwd test usermod -G gitgroup test 将test账号的组改为和git一样的组gitgroup git所在 ...
- 搭建简单的SpringCloud项目二:服务层和消费层
GitHub:https://github.com/ownzyuan/test-cloud 前篇:搭建简单的SpringCloud项目一:注册中心和公共层 后篇:搭建简单的SpringCloud项目三 ...
- matplotlib以对象方式绘制子图
matplotlib有两种绘图方式,一种是基于脚本的方式,另一种是面向对象的方式 面向脚本的方式类似于matlab,面向对象的方式使用起来更为简便 创建子图的方式也很简单 fig,ax = plt.s ...
- Docker环境中部署Prometheus及node-exporter监控主机资源
前提条件 已部署docker 已部署grafana 需要开放 3000 9100 和 9090 端口 启动node-exporter docker run --name node-exporter - ...
- Freeswitch 安装爬坑记录1
2 Freeswitch的安装 2.1 准备工作 服务器安装CentOS 因为是内部环境,可以关闭一些防火墙设置,保证不会因为网络限制而不能连接 关闭防火墙 查看防火墙 systemctl statu ...
- LeetCode两数之和
LeetCode 两数之和 题目描述 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是 ...
- aboard, abolish
aboard board做动词有上车/船/飞机的意思,boarding就是正在上.board做名词有板的意思,车厢地板的板. a是个词根,有三种意思:1. 以某种状态或方式,如: ablaze, af ...
- CAD简介
Computer-aided design (CAD) is the use of computers (or workstations) to aid in the creation, modifi ...
- 零基础学习java------25--------jdbc
jdbc开发步骤图 以下要用到的products表 一. JDBC简介 补充 JDBC本质:其实是官方(sun公司)定义的一套操作所有关系型数据库的规则,即接口,各个数据库厂商趋势线这个接口,提 ...
- 案例 stm32单片机,adc的双通道+dma 内部温度
可以这样理解 先配置adc :有几个通道就配置几个通道. 然后配置dma,dma是针对adc的,而不是针对通道的. 一开始我以为一个adc通道对应一个dma通道.(这里是错的,其实是我想复杂了) 一个 ...