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)
解説
-同時に:return isSubsequence(a.slice(1)、b.slice(1);
-異なる場合:return isSubsequence(a,b.slice(1);
このような条件を与えて再帰的に解決することもできる.
Reference
この問題について(isSubsequenceの問題の解決), 我々は、より多くの情報をここで見つけました https://velog.io/@stthunderl/isSubsequence-문제풀이テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol