isSubsequenceの問題の解決

5594 ワード

説明する

/*
 문제
	Write a function called isSubsequence
	which takes in two strings and checks
	whether the characters in the first string
	form a subsequence of the characters in the second string.
	In other words, the function should check
	whether the characters in the first string
	appear somewhere in the second string,
	without their order changing.

	Your solution MUST have AT LEAST the following complexities:
		Time Complexity - O(N + M)
		Space Complexity - O(1)
 */
function isSubsequence(a, b) {
    let idxA = 0;
    let idxB = 0;
    while (idxA < a.length && idxB < b.length) {
        if (a[idxA] === b[idxB]) {
            idxA++;
            idxB++;
        } else {
            idxB++;
        }
    }
    if (idxA === a.length) {
        return true;
    } else {
        return false;
    }
}
console.log(isSubsequence('hello', 'hello world')); // true
console.log(isSubsequence('sing', 'sting')); // true
console.log(isSubsequence('abc', 'abracadabra')); // true
console.log(isSubsequence('abc', 'acb')); // false (order matters)

解説

  • インデックスを移動して解除しました.
  • whileゲートが脱出した場合、idxAがa.lengthに等しい場合は、すべての単語を含むことを示す->true
  • でない場合false
  • の複文で説明することもできます.

  • -同時に:return isSubsequence(a.slice(1)、b.slice(1);
    -異なる場合:return isSubsequence(a,b.slice(1);
    このような条件を与えて再帰的に解決することもできる.