-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImplementStrStr.kt
60 lines (49 loc) · 1.54 KB
/
ImplementStrStr.kt
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
package problems
class ImplementStrStr {
//Apparenlty, Brute is the suggested method
fun strStrBrute(haystack: String, needle: String): Int {
if (needle.isEmpty()) return 0
for (i in 0 until haystack.length - needle.length + 1) {
var isMatching = false
for (j in 0 until needle.length) {
if (haystack[j + i] == needle[j]) {
isMatching = true
} else {
isMatching = false
break
}
}
if (isMatching) {
return i
}
}
return -1
}
//Does not work - tried scanning method and failed to spot needle duplicates.
fun strStr(haystack: String, needle: String): Int {
if (needle.isEmpty()) return 0
var matchCounter = 0
var startingIndex = -1
for (i in 0 until haystack.length) {
if (matchCounter < needle.length) {
//not yet found
if (haystack[i] == needle[matchCounter]) {
if (matchCounter == 0) {
//initial found
startingIndex = i
}
matchCounter++
} else {
startingIndex = -1
matchCounter = 0
}
} else {
//found
}
}
if (matchCounter != needle.length) {
startingIndex = -1
}
return startingIndex
}
}