码迷,mamicode.com
首页 > 其他好文 > 详细

791. Custom Sort String字符串保持字母一样,位置可以变

时间:2018-08-05 00:29:18      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:idt   turn   more   tst   number   tostring   har   rev   while   

[抄题]:

S and T are strings composed of lowercase letters. In S, no letter occurs more than once.

S was sorted in some custom order previously. We want to permute the characters of T so that they match the order that S was sorted. More specifically, if x occurs before y in S, then x should occur before y in the returned string.

Return any permutation of T (as a string) that satisfies this property.

Example :
Input: 
S = "cba"
T = "abcd"
Output: "cbad"
Explanation: 
"a", "b", "c" appear in S, so the order of "a", "b", "c" should be "c", "b", and "a". 
Since "d" does not appear in S, it can be at any position in T. "dcba", "cdba", "cbda" are also valid outputs.

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

大体思路是对的:先差后s,但是还可以优化一下:先s后差。

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[一句话思路]:

粘贴差字母的时候,从26个字母a-z逐个入手即可。

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

技术分享图片

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

粘贴差字母的时候,从26个字母a-z逐个入手即可。

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[算法思想:迭代/递归/分治/贪心]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

 [是否头一次写此类driver funcion的代码] :

 [潜台词] :

技术分享图片
class Solution {
    public String customSortString(String S, String T) {
        //corner case
        if (S == null || T == null) return "";
        
        //initialization: int[26], count char
        int[] count = new int[26];
        for (char t : T.toCharArray()) {
            count[t - ‘a‘]++;
        }

        StringBuilder sb = new StringBuilder();
        //append s
        for (char s : S.toCharArray()) {
            while (count[s - ‘a‘]-- > 0) 
                sb.append(s);
        }
        
        //append t - s from a to z
        for (char c = ‘a‘; c <= ‘z‘; c++) {
            while (count[c - ‘a‘]-- > 0) 
                sb.append(c);
        }
        
        return sb.toString();
    }
}
View Code

 

791. Custom Sort String字符串保持字母一样,位置可以变

标签:idt   turn   more   tst   number   tostring   har   rev   while   

原文地址:https://www.cnblogs.com/immiao0319/p/9420562.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!