【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 ...
随机推荐
- CentOS6.9安装python3
安装依赖包: yum install -y openssl-devel bzip2-devel expat-devel gdbm-devel readline-devel sqlite-devel w ...
- 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 ...
- 突破冯·诺依曼架构瓶颈!全球首款存算一体AI芯片诞生
过去70年,计算机一直遵循冯·诺依曼架构设计,运行时数据需要在处理器和内存之间来回传输. 随着时代发展,这一工作模式面临较大挑战:在人工智能等高并发计算场景中,数据来回传输会产生巨大的功耗:目前内存系 ...
- day34 前端基础之JavaScript
day34 前端基础之JavaScript ECMAScript 6 尽管 ECMAScript 是一个重要的标准,但它并不是 JavaScript 唯一的部分,当然,也不是唯一被标准化的部分.实际上 ...
- Flink(九)【Flink的重启策略】
目录 1.Flink的重启策略 2.重启策略 2.1未开启checkpoint 2.2开启checkpoint 1)不设置重启策略 2)不重启 3)固定延迟重启(默认) 4)失败率重启 3.重启效果演 ...
- Linux学习 - 环境变量配置文件
一.环境变量配置文件的作用 /etc/profile /etc/profile.d/*.sh ~/.bash_profile ~/.bashrc /etc/bashrc 1 /etc/profile的 ...
- Linux基础命令---mysql
mysql mysql是一个简单的sql shell,它可以用来管理mysql数据库. 此命令的适用范围:RedHat.RHEL.Ubuntu.CentOS.Fedora. 1.语法 m ...
- clickhouse安装数据导入及查询测试
官网 https://clickhouse.tech/ quick start ubantu wget https://repo.yandex.ru/clickhouse/deb/lts/main/c ...
- 【Linux】【Basis】Grub
GRUB(Boot Loader): 1. grub: GRand Unified Bootloader grub 0.x: grub legacy grub 1.x: grub2 2. gr ...
- SpringBoot环境下java实现文件的下载
思路:文件下载,就是给服务器上的文件创建输入流,客户端创建输出流,将文件读出,读入到客户端的输出流中,(流与流的转换) package com.cst.icode.controller; import ...