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

自定义字符串排序【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.

给定两个字符串 ordersorder 的所有单词都是 唯一 的,并且以前按照一些自定义的顺序排序。

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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值