【每日一题DAY26】LC791自定义字符串排序 | 哈希表计数

简介: 对 s 的字符进行置换,使其与排序的 order 相匹配。更具体地说,如果在 order 中的字符 x 出现字符 y 之前,那么在排列后的字符串中, x 也应该出现在 y 之前。

自定义字符串排序【LC791】


You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously.


Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string.


Return any permutation of s that 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 ( 26 )
目录
相关文章
|
9月前
【每日一题Day176】LC2404出现最频繁的偶数元素 | 哈希表
【每日一题Day176】LC2404出现最频繁的偶数元素 | 哈希表
64 0
【每日一题Day176】LC2404出现最频繁的偶数元素 | 哈希表
|
9月前
|
机器学习/深度学习
【每日一题Day120】LC2341数组能形成多少数对 | 哈希表 排序
【每日一题Day120】LC2341数组能形成多少数对 | 哈希表 排序
51 0
|
9月前
|
存储
【每日一题Day158】LC2395和相等的子数组 | 哈希表
【每日一题Day158】LC2395和相等的子数组 | 哈希表
44 0
|
9月前
【每日一题Day340】LC2251花期内花的数目 | 差分+哈希表+排序 排序+二分查找
【每日一题Day340】LC2251花期内花的数目 | 差分+哈希表+排序 排序+二分查找
42 0
|
9月前
|
算法
【每日一题Day229】LC2352相等行列对 | 哈希
【每日一题Day229】LC2352相等行列对 | 哈希
55 0
|
9月前
|
存储
【每日一题Day132】LC23633合并相似的物品 | 哈希表 排序+双指针
【每日一题Day132】LC23633合并相似的物品 | 哈希表 排序+双指针
66 0
|
9月前
|
存储
【每日一题Day307】LC56合并区间 | 排序
【每日一题Day307】LC56合并区间 | 排序
51 0
|
9月前
|
机器学习/深度学习
【每日一题Day128】LC2357使数组中所有元素都等于零 | 排序+模拟 哈希表
【每日一题Day128】LC2357使数组中所有元素都等于零 | 排序+模拟 哈希表
37 0
|
9月前
|
存储
【每日一题Day352】LC1726同积元组 | 哈希表+排列组合
【每日一题Day352】LC1726同积元组 | 哈希表+排列组合
46 0
|
9月前
【每日一题Day252】LC1两数之和 | 哈希表
【每日一题Day252】LC1两数之和 | 哈希表
46 0

热门文章

最新文章