Skip to content

Commit c6daedd

Browse files
committed
longest common substring
1 parent 8c30ebb commit c6daedd

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

longest_common_substring.rb

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
def LCSLength (x, y)
2+
h = Array.new(x.size) {Array.new(y.size)}
3+
x.size.times {|i| h[i][0] = x[0] == y[0] ? 1 : 0 }
4+
y.size.times {|i| h[0][i] = x[0] == y[0] ? 1 : 0 }
5+
6+
(1..x.size-1).each do |i|
7+
(1..y.size-1).each do |j|
8+
if x[i] == y[j]
9+
h[i][j] = (h[i-1][j-1] ? h[i-1][j-1] : 0) + 1
10+
else
11+
h[i][j] = [ h[i-1][j] ? h[i-1][j] : 0, h[i][j-1] ? h[i][j-1] : 0].max
12+
end
13+
end
14+
end
15+
h[x.size-1][y.size-1]
16+
end
17+
18+
19+
p LCSLength('waaaa', 'bbbbasfaaewra') #returns 4

0 commit comments

Comments
 (0)