作者: 负雪明烛
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. EXCEL-如何在excel中对图片进行批量排版

    新建EXCEL->导入图片->如果每张图高度为33个单元格,共计10张图,那么将最后边的那张图(即正对着你的那一张)剪切粘贴到33*9行第一个单元格处->按F5定位"对象& ...

  2. STM32 BootLoader升级固件

    一.知识点 1.BootLoader就是单片机启动时候运行的一段小程序,这段程序负责单片机固件的更新,也就是单片机选择性的自己给自己下程序.可以更新,也可以不更新,更新的话,BootLoader更新完 ...

  3. centos yum安装mongodb,php扩展

    一,安装mongodb,php扩展 ? 1 [root@localhost ~]# yum install php-pecl-mongo mongodb mongodb-devel mongodb-s ...

  4. keepalived+nginx安装

    安装keepalived+nginx做为公司服务器前端高可用反向代理安装nginx 1.yum install -y pcre pcre-devel gcc-c++ zlib zlib-devel o ...

  5. day07 MySQL索引事务

    day07 MySQL索引事务 昨日内容回顾 pymysql模块 # 链接数据库都是使用这个模块的 # 创建链接 import pymysql conn = pymysql.connect( host ...

  6. Spark(十六)【SparkStreaming基本使用】

    目录 一. SparkStreaming简介 1. 相关术语 2. SparkStreaming概念 3. SparkStreaming架构 4. 背压机制 二. Dstream入门 1. WordC ...

  7. tomcat启动和停止脚本

    #!/bin/bash JDK_HOME=/apps/jdk1.7.0_79 CATALINA_HOME=/apps/tomcat export JDK_HOME CATALINA_HOME sour ...

  8. Android 高级UI组件(三)

    一.popupWindow 1.AlertDialog和PopupWindow最关键的区别是AlertDialog不能指定显示位置,只能默认显示在屏幕最中间(当然也可以通过设置WindowManage ...

  9. html5 绘图

    SVG 在 SVG 中,每个元素是图型与数据相结合的一个对象. 修改对象属性的值,图型会立即体现出这种变化. 因为是对象,所以支持事件处理. D3使用的是SVG Canvas 不支持事件处理. cha ...

  10. java职业路线图