[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 most 26, and no character is repeated in order.
  • str has length at most 200.
  • order and str 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的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程