Skip to content

Commit eca7e99

Browse files
committed
2981
1 parent 7c28fed commit eca7e99

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# @param {String} s
2+
# @return {Integer}
3+
def maximum_length(s)
4+
max = -1
5+
counter = Hash.new(0)
6+
(0...s.length).each { |i|
7+
(i...s.length).each { |j|
8+
break if s[j] != s[i]
9+
10+
sub = s[i..j]
11+
counter[sub] += 1
12+
if counter[sub] >= 3
13+
max = [max, j-i+1].max
14+
end
15+
}
16+
}
17+
18+
max
19+
end
20+
21+
# optimize
22+
def maximum_length(s)
23+
counter = Array.new(26) { Array.new(s.length+1, 0) }
24+
25+
prev = nil
26+
len = 1
27+
s.each_char { |c|
28+
if prev == c
29+
counter[c.ord - 97][len += 1] += 1
30+
else
31+
len = 1
32+
counter[c.ord - 97][len] += 1
33+
prev = c
34+
end
35+
}
36+
37+
max = -1
38+
(0..25).each { |i|
39+
len = s.length
40+
# a substring with len has 2 substring with len-1, prefix and suffix
41+
count = 0
42+
while len >= 1
43+
count += counter[i][len]
44+
if count >= 3
45+
max = len if max < len
46+
break
47+
end
48+
len -= 1
49+
end
50+
}
51+
52+
max
53+
end

0 commit comments

Comments
 (0)