Common Sub-String
Aizu Online Judge。2 個の文字列が与えられたとき, 両方の文字列に含まれる文字列のうち最も長いも のを探し, その長さを答えるプログラム。
Rubyのサンプルソース
123456789101112131415161718192021
loop dos, t= gets.chomp, gets.chomp rescue breaks, t= t, s if s.length > t.length
max_l=(s.chars & t.chars).map do |a|
[s.count(a), t.count(a)].min
end.inject(:+).to_i
answer= 0
0.upto(t.length).each do |i|
break if t.length - i <= answer
max=[max_l+1, t.length - i + 1].min - 1
(answer + 1).upto(max)do |j|
if s.include?(t[i...i+j])answer= j
elsebreakend
end
end
puts answer
end
Pythonのサンプルソース
1234567891011121314151617
while True:
try:
s, t= raw_input(), raw_input()if len(s) < len(t): s, t= t, s
MAXL= sum(min(s.count(i), t.count(i))for i in set(list(s)) & set(list(t)))ans= 0
for sp in range(len(t)):
if len(t) - sp <= ans:
breakfor l in range(ans+1, min(MAXL+1, len(t)-sp+1)):
if t[sp:sp+l] in s:
ans= l
else:
breakprint ans
except:
break