自定义字符串排序【LC791】
You are given two strings order and s. All the characters of
orderare unique and were sorted in some custom order previously.Permute the characters of
sso that they match the order thatorderwas sorted. More specifically, if a characterxoccurs before a characteryinorder, thenxshould occur beforeyin the permuted string.Return any permutation of
sthat satisfies this property.
给定两个字符串
order和s。order的所有单词都是 唯一 的,并且以前按照一些自定义的顺序排序。对
s的字符进行置换,使其与排序的order相匹配。更具体地说,如果在order中的字符x出现字符y之前,那么在排列后的字符串中,x也应该出现在y之前。返回 满足这个性质的
s的任意排列 。
参加了双周赛+周赛,都只A了2.5题,最后一题就都只卡了一点点,好气,下周继续努力
-
思路:先使用哈希表统计字符串s中出现的字母和个数,然后将字母按order的顺序进行构造,order中不存在的字母按照字典顺序进行存放
-
实现
class Solution { public String customSortString(String order, String s) { int[] flag = new int[26]; StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++){ flag[s.charAt(i) - 'a']++; } for (int i = 0; i < order.length(); i++){ char c = order.charAt(i); while (flag[c - 'a'] > 0){ sb.append(c); flag[c-'a']--; } } for (int i = 0; i < flag.length; i++){ while (flag[i] > 0){ sb.append((char)('a' + i)); flag[i]--; } } return new String(sb); } }-
复杂度
- 时间复杂度:O(n+m)O(n+m)O(n+m)
- 空间复杂度:O(26)O(26)O(26)
-

本文介绍如何使用Python实现字符串s的字符排序,使其遵循给定的自定义顺序order。通过哈希表统计s中字符频率,然后按照order中的字符顺序填充,最后处理order中未出现的字符。适合解决字符串排序问题。
2万+

被折叠的 条评论
为什么被折叠?



