Skip to content

Commit 1774f1a

Browse files
multiple pointer program added
1 parent 710a8a2 commit 1774f1a

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
2+
// Write a function called isSubsequence which takes in two strings and checks whether the characters
3+
// in the first string form a subsequence of the characters in the second string.
4+
// In other words, the function should check whether the characters in the first string appear somewhere
5+
// in the second string, without their order changing.
6+
7+
console.log('------------- solution 1 ---------------')
8+
const isSubsequence = (str1, str2) => {
9+
10+
var i = 0;
11+
var j = 0;
12+
if (!str1) return true;
13+
while (j < str2.length) {
14+
console.log(i, str1.length)
15+
if (str2[j] === str1[i]) i++;
16+
if (i === str1.length) return true;
17+
j++;
18+
}
19+
return false;
20+
}
21+
22+
console.log(isSubsequence('hello', 'hello world')); // true
23+
console.log(isSubsequence('sing', 'sting')); // true
24+
console.log(isSubsequence('abc', 'abracadabra')); // true
25+
console.log(isSubsequence('abc', 'acb')); // false (order matters)
26+
27+
console.log('------------- solution 2 ---------------')
28+
const isSubsequence2 = (str1, str2) => {
29+
30+
if (str1.length === 0) return true
31+
if (str2.length === 0) return false
32+
if (str2[0] === str1[0]) return isSubsequence2(str1.slice(1), str2.slice(1))
33+
return isSubsequence2(str1, str2.slice(1))
34+
}
35+
36+
console.log(isSubsequence2('hello', 'hello world')); // true
37+
console.log(isSubsequence2('sing', 'sting')); // true
38+
console.log(isSubsequence2('abc', 'abracadabra')); // true
39+
console.log(isSubsequence2('abc', 'acb')); // false (order matters)

0 commit comments

Comments
 (0)