LeetCode Custom Sort String 问题

题目是这样的:

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.

 

Note:

  • S has length at most 26, and no character is repeated in S.
  • T has length at most 200.
  • S and T consist of lowercase letters only.

这个题目的意思可以理解为:新生成一个字符串,生成规则是:将字符串T中所有的在S中存在的字符按照S的顺序来排列,另外,在T中存在而在S中不存在的字符直接拼接上,可以为乱序,但是在S中存在的字符一定要按照S的顺序拼接,并且在T中出现多次,在S中出现一次的字符需要拼接到S中和这个字符相同位置的前或后

用比较笨的方法:就是分析可能出现的几种情况

public static String customSortString(String S, String T) {
        char[] chars = T.toCharArray();
        String map = "";
        String tem = "";
        for (int i=0;i<chars.length;i++){
            if(map.contains(chars[i]+"")&&S.contains(chars[i]+"")){
                String SBegin = S.substring(0,S.indexOf(chars[i]));
                String SEnd = S.substring(S.indexOf(chars[i]),S.length());
                S = SBegin + chars[i] + SEnd;
            }else if(!S.contains(chars[i]+"")){
                tem += chars[i];
            }
            map += chars[i];
        }
        return S+tem;
    }

第一种情况是在T中出现,在S中没有出现的字符,这些字符是一定要拼接到最终字符串上的,用了个tem字符串来统计;
第二种情况比较麻烦,就是在T中出现过多次,在S中也出现的字符,原先是用的replaceAll来做的,但是发现不行,replaceAll方法把全部的字符都替换了,所以Complite Error了。
可以这样,既然这个字符在S中出现了,还需要在S中相同位置的前后拼接,那么就重新拼接S,并且通过切割字符串将这个字符拼到要求的位置




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值