Javascript Codewars Challenge(isMerge)

后端 未结 4 1427
天涯浪人
天涯浪人 2021-01-29 15:53

I have asked this question before (the first link to my question) but couldn\'t get the complete solution for the question. Write an algorithm to check if a given string, s, can

4条回答
  •  半阙折子戏
    2021-01-29 16:28

    Try something like:

    function mergeCheck(s, p1, p2, i, j, k) {
        if (i == s.length) {
            return true;
        } else {
            if (s[i] == p1[j]) {
                j++;
            } else if (s[i] == p2[k]) {
                k++;
            } else {
                return false;
            }
            i++;
            return mergeCheck(s, p1, p2, i, j, k);
        }
    }
    
    function isMerge(s, p1, p2) {
        if (s.length == (p1.length + p2.length)) {
            return mergeCheck(s, p1, p2, 0, 0, 0);
        }
        else {
        	return false;
        }
    }
    console.log(isMerge("codewars", "cdw", "oears"))
    console.log(isMerge("codewars", "cw", "oears"))
    console.log(isMerge("codewars", "cdwx", "oears"))

    It starts at the beginning of the s string and compares the letter in question with the letters next in sequence for p1 or p2. If a match is found in either of them, it moves forward and checks the subsequent letters until it finds a mismatch or reaches the end of s

提交回复
热议问题