-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.rb
More file actions
78 lines (51 loc) · 1.23 KB
/
Solution.rb
File metadata and controls
78 lines (51 loc) · 1.23 KB
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
77
78
# @param {String} haystack
# @param {String} needle
# @return {Integer}
def str_str(haystack, needle)
if haystack.nil? or needle.nil? or haystack.size < needle.size
return -1
end
if needle.size < 1
return 0
end
nextVector = makeNextVector needle
hsSize = haystack.size; nSize = needle.size
hayStackIndex = 0; needleIndex = 0
while hayStackIndex < hsSize
while needleIndex > 0 and needle[needleIndex] != haystack[hayStackIndex]
needleIndex = nextVector[needleIndex - 1]
end
if needle[needleIndex] == haystack[hayStackIndex]
needleIndex += 1
end
if needleIndex == nSize
return hayStackIndex - nSize + 1
end
hayStackIndex += 1
end
return -1
end
def makeNextVector(patternStr)
if patternStr.size < 2
return [0]
end
patternSize = patternStr.size
nextVector = Array.new(patternSize)
nextVector[0] = 0
index = 1; k = 0
while index < patternSize
while k > 0 and patternStr[k] != patternStr[index]
k = nextVector[k - 1]
end
if patternStr[k] == patternStr[index]
k += 1
end
nextVector[index] = k
index += 1
end
nextVector
end
# puts str_str '', ''
puts str_str 'babba', 'bbb'
puts str_str 'a', ''
# puts ''.nil?