-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.js
executable file
·76 lines (63 loc) · 2.23 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#!/usr/bin/env node
// Problem description at -> https://leetcode.com/problems/implement-strstr/
'use strict';
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function (haystack, needle) {
if (needle.length == 0) return 0;
if (needle.length > haystack.length) return -1;
// First solution
const splitted = haystack.split(needle);
return splitted.length > 1 ? splitted[0].length : -1;
};
// // Second solution
// var strStr = function (haystack, needle) {
// if (needle.length == 0) return 0;
// if (needle.length > haystack.length) return -1;
// // // First solution
// // return haystack.split(needle).length > 1 ? haystack.split(needle)[0].length : -1;
// for (let i = 0; i < haystack.length; i++) {
// let x = 0;
// let indices = [];
// let isFound = false;
// for (let j = i; j < haystack.length; j++) {
// if (haystack[j] == needle[x]) {
// isFound = true;
// x++;
// indices.push(j);
// } else {
// isFound = false;
// x = 0
// indices = [];
// break;
// }
// if (x >= needle.length) {
// break;
// }
// }
// if (isFound) {
// if (indices.length == 1 && needle.length > 1 || x < needle.length) return -1;
// return indices[0]
// }
// }
// return -1;
// };
// var strStr = function (haystack, needle) {
// if (needle.length == 0) return 0;
// if (needle.length > haystack.length) return -1;
// // Third solution using regular expressions
// const regex = new RegExp(`${needle}`);
// return haystack.search(regex);
// };
// console.log(strStr('Hello', 'll')); // 2
// console.log(strStr('mississippi', 'issip')); // 4
// console.log(strStr('mississippi', 'issi')); // 1
// console.log(strStr('mississippi', 'issipi')); // -1
// console.log(strStr('mississippi', 'i')); // 1
// console.log(strStr('mississippi', 'pi')); // 9
// console.log(strStr('aaaaa', 'babba')); // -1
// console.log(strStr('aabaaabaaac', 'aabaaac')); // 4
// console.log(strStr('mississippi', 'sippia')); // -1