[LeetCode] 791. Custom Sort String
2021/7/15 6:07:57
本文主要是介绍[LeetCode] 791. Custom Sort String,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
order
and str
are strings composed of lowercase letters. In order
, no letter occurs more than once.
order
was sorted in some custom order previously. We want to permute the characters of str
so that they match the order that order
was sorted. More specifically, if x
occurs before y
in order
, then x
should occur before y
in the returned string.
Return any permutation of str
(as a string) that satisfies this property.
Example: Input: order = "cba" str = "abcd" Output: "cbad" Explanation: "a", "b", "c" appear in order, so the order of "a", "b", "c" should be "c", "b", and "a". Since "d" does not appear in order, it can be at any position in the returned string. "dcba", "cdba", "cbda" are also valid outputs.
Note:
order
has length at most26
, and no character is repeated inorder
.str
has length at most200
.order
andstr
consist of lowercase letters only.
自定义字符串排序。
字符串S和 T 只包含小写字符。在S中,所有字符只会出现一次。
S 已经根据某种规则进行了排序。我们要根据S中的字符顺序对T进行排序。更具体地说,如果S中x在y之前出现,那么返回的字符串中x也应出现在y之前。
返回任意一种符合条件的字符串T。
示例:
输入:
S = "cba"
T = "abcd"
输出: "cbad"
解释:
S中出现了字符 "a", "b", "c", 所以 "a", "b", "c" 的顺序应该是 "c", "b", "a".
由于 "d" 没有在S中出现, 它可以放在T的任意位置. "dcba", "cdba", "cbda" 都是合法的输出。
注意:S的最大长度为26,其中没有重复的字符。
T的最大长度为200。
S和T只包含小写字符。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/custom-sort-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路是 counting sort 计数排序。根据题意,S是规则,T是需要被排序的字符串。首先我们统计一下在T中,每个字母分别出现了几次。统计好了之后,我们按照规则的顺序,分别检查在规则中出现的字母,是否也出现在T中,如果有,则将T中所有的字母都写入 StringBuilder。最后对于T中出现但是S中未出现的字母,我们加到 StringBuilder 的最后即可。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public String customSortString(String order, String str) { 3 int[] count = new int[26]; 4 for (char c : str.toCharArray()) { 5 count[c - 'a']++; 6 } 7 8 StringBuilder sb = new StringBuilder(); 9 for (char c : order.toCharArray()) { 10 while (count[c - 'a'] > 0) { 11 sb.append(c); 12 count[c - 'a']--; 13 } 14 } 15 for (char c = 'a'; c <= 'z'; c++) { 16 while (count[c - 'a'] > 0) { 17 sb.append(c); 18 count[c - 'a']--; 19 } 20 } 21 return sb.toString(); 22 } 23 }
LeetCode 题目总结
这篇关于[LeetCode] 791. Custom Sort String的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-23DevExpress 怎么实现右键菜单(Context Menu)显示中文?-icode9专业技术文章分享
- 2024-12-22怎么通过控制台去看我的页面渲染的内容在哪个文件中呢-icode9专业技术文章分享
- 2024-12-22el-tabs 组件只被引用了一次,但有时会渲染两次是什么原因?-icode9专业技术文章分享
- 2024-12-22wordpress有哪些好的安全插件?-icode9专业技术文章分享
- 2024-12-22wordpress如何查看系统有哪些cron任务?-icode9专业技术文章分享
- 2024-12-21Svg Sprite Icon教程:轻松入门与应用指南
- 2024-12-20Excel数据导出实战:新手必学的简单教程
- 2024-12-20RBAC的权限实战:新手入门教程
- 2024-12-20Svg Sprite Icon实战:从入门到上手的全面指南
- 2024-12-20LCD1602显示模块详解