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.

给出S,T两个字符串,S字符串是不重复且自定义排序的,需要根据S的自定义排序规则重组T字符串并且返回

   /**
     * 使用Map记录T中字符在S中出现的位置并且记录当前T中的字符
     * 在T中有重复字符在S中出现的情况下需要把Map中的值取出并且累加再放在Map中,这样可以防止结果中漏掉T中重复有效的数据
     * @param S
     * @param T
     * @return
     */
    public String customSortString(String S, String T) {
        char[] schars = T.toCharArray();
        Map map = new HashMap();
        StringBuilder result = new StringBuilder("");
        int count = 0;
        for(char sc : schars){
            int index = S.indexOf(sc+"");
            if(index >= 0){
                String tmp = sc + "" ;
                if(map.containsKey(index)){
                    tmp = map.get(index) + sc + "" ;
                }
                map.put(index, tmp);
                count ++;
            }else{
                result.append(sc);
            }
        }

        for(int i = 0; i < count; i++){
            if(map.containsKey(i)){
                result.append(map.get(i));
            }
        }
        return result.toString();
    }

你可能感兴趣的:(Custom Sort String)