Recover a secret string from random triplets

题目

There is a secret string which is unknown to you. Given a collection of random triplets from the string, recover the original string.

A triplet here is defined as a sequence of three letters such that each letter occurs somewhere before the next in the given string. “whi” is a triplet for the string “whatisup”.

As a simplification, you may assume that no letter occurs more than once in the secret string.

You can assume nothing about the triplets given to you other than that they are valid triplets and that they contain sufficient information to deduce the original string. In particular, this means that the secret string will never contain letters that do not occur in one of the triplets given to you.

分析

题目里说了,输入的都是3长度的固定数组,而且没有重复字符。那么就可以先把数组里重复的字符去掉,然后组成一个新的字符串。然后取出每个数组里的两个字符串对比位置是否正确。不正确的就对调字符位置。

其他的看注释。

答案

var recoverSecret = function (triplets) {
    let t_string = "";
    // 把所有字符放到一个字符串里,并且去掉重复字符串
    for (let i in triplets) {
        for (let k in triplets[i]) {
            if (t_string.indexOf(triplets[i][k]) === -1) {
                t_string += triplets[i][k];
            }
        }
    }
    // 设定循环标记为true
    let loop = true
    while (loop === true) {
        // 将循环标记为false
        loop = false
        // 输入数组的顺序进行对比,如果有顺序不一致的,就把字符的位置对调,直到顺序全部正确
        // 先取出triplets里面的元素
        for (let i = 0; i < triplets.length; i++) {
            // 取出每个数组里的两个元素
            for (let j = 0; j < 2; j++) {
                let arr = triplets[i].slice(j, j + 2);
                // 查找两个元素在t_string里的位置,如果位置相反就对调
                if (t_string.indexOf(arr[0]) > t_string.indexOf(arr[1])) {
                    t_string = t_string.replace(arr[0], arr[1]).replace(arr[1], arr[0]);
                    //因为字符串顺序有修改,所以讲循环标记重新设定为true
                    loop = true;
                }
            }
        }
    }
    return t_string
}