【Lintcode】1025. Custom Sort String

题目地址:

https://www.lintcode.com/problem/custom-sort-string/description

给定两个字符串 s s s t t t,题目保证两者都只含英文小写字母,并且 s s s里无重复字母。要求重排 t t t,使得 t t t的字母顺序是按照 s s s里字母顺序定义的。不在 s s s里的字母随便排在哪儿。返回任意一个重排的结果即可。

先统计一下 t t t的每个字母出现次数,以哈希表 c c c表示,然后再遍历 s s s,如果 s [ i ] s[i] s[i]出现了,则append到一个StringBuilder后面 c [ s [ i ] ] c[s[i]] c[s[i]]这么多次。最后再把没出现的字母也依次append到StringBuilder后面即可。代码如下:

public class Solution {
    /**
     * @param S: The given string S
     * @param T: The given string T
     * @return: any permutation of T (as a string) that satisfies this property
     */
    public String customSortString(String S, String T) {
        // Write your code here
        int[] count = new int[26];
        for (int i = 0; i < T.length(); i++) {
            count[T.charAt(i) - 'a']++;
        }
        
        StringBuilder sb = new StringBuilder();
        // 先处理S里有的字母
        for (int i = 0; i < S.length(); i++) {
            int idx = S.charAt(i) - 'a';
            while (count[idx] > 0) {
                sb.append((char) ('a' + idx));
                count[idx]--;
            }
        }
    
    	// 再处理没有的
        for (int i = 0; i < count.length; i++) {
            if (count[i] == 0) {
                continue;
            }
    
            for (int j = 0; j < count[i]; j++) {
                sb.append((char) ('a' + i));
            }
        }
        
        return sb.toString();
    }
}

时空复杂度 O ( l t ) O(l_t) O(lt)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值