作者: 负雪明烛
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:

  1. S has length at most 26, and no character is repeated in S.
  2. T has length at most 200.
  3. 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++)的更多相关文章

  1. LeetCode 791. Custom Sort String

    题目链接:https://leetcode.com/problems/custom-sort-string/description/ S and T are strings composed of l ...

  2. [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 ...

  3. 【LeetCode】481. Magical String 解题报告(Python)

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

  4. 791. Custom Sort String - LeetCode

    Question 791. Custom Sort String Solution 题目大意:给你字符的顺序,让你排序另一个字符串. 思路: 输入参数如下: S = "cba" T ...

  5. 【LeetCode】87. Scramble String 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 动态规划 日期 题目地址:https://le ...

  6. 【LeetCode】796. Rotate String 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  7. 【LeetCode】148. Sort List 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  8. 【LeetCode】767. Reorganize String 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.me/ 题目地址:https://leetcode.com/problems/reorganiz ...

  9. 【LeetCode】344. Reverse String 解题报告(Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 新构建字符串 原地翻转 日期 题目地址:https://lee ...

随机推荐

  1. SQL- case when then else end 用法经验总结

    对case when 的理解总结: 1.then和else后,只能写一条输出语句且输出结果就是新生成列的值;when 后的条件判断可以有多条,且可以多个字段联合判断:end 后的输出也可以有多条,但必 ...

  2. Docker Swarm的命令

    初始化swarm manager并制定网卡地址docker swarm init --advertise-addr 192.168.10.117 强制删除集群docker swarm leave -- ...

  3. 【c++】解析多文件编程的原理

    其实一直搞不懂为什么头文件和其他cpp文件之间的关系,今晚索性一下整明白 [c++]解析多文件编程的原理 a.cpp #include<stdio.h> int main(){ a(); ...

  4. Spring MVC入门(二)—— URI Builder模式

    URI Builder Spring MVC作为一个web层框架,避免不了处理URI.URL等和HTTP协议相关的元素,因此它提供了非常好用.功能强大的URI Builder模式来完成,这就是本文重点 ...

  5. pandas基础学习一

    生成对象 用值列表生成 Series 时,Pandas 默认自动生成整数索引: In [3]: s = pd.Series([1, 3, 5, np.nan, 6, 8]) In [4]: s Out ...

  6. 设计模式学习笔记之看懂UML类图

    什么是UML: UML(统一建模语言)是当今软件设计的标准图标式语言.对于一个软件系统而言,UML语言具有以下的功能:可视化功能.说明功能.建造功能和建文档功能. UML都包括什么类型的图: 使用案例 ...

  7. [笔记] Informer: Beyond Efficient Transformer for Long Sequence Time-Series Forecasting

    原文地址:https://arxiv.org/abs/2012.07436 源码地址:https://github.com/zhouhaoyi/Informer2020

  8. 沉淀vue相关知识(主要还是个人积累用)

    路由懒加载的配置: const Home= () =>import('../components/Home') //使用ES6中的路由懒加载的方式 const About= () =>im ...

  9. 车载以太网第二弹|测试之实锤-TC8 TCP/IP协议一致性测试实践

    前言 车载以太网测试实践系列,我们还分享了PMA测试实践.IOP测试实践 .本期给大家介绍的是TC8中的TCP/IP协议一致性测试(以下简称TCP/IP测试). TCP/IP测试-设备环境组成 TTw ...

  10. 安装MySQL5.7.26教程图解

    安装MySQL5.7.26教程图解 1.安装mysql所需的yum源 yum -y install gcc-c++ ncurses-devel cmake make perl gcc autoconf ...