题解 | #公共子串计算#

公共子串计算

http://www.nowcoder.com/practice/98dc82c094e043ccb7e0570e5342dd1b

分析

s1: asd
s2: werasd
定义 map[i][j] 为s1[0..i],s2[0..j]的最长子串长度

0 1 2
0 0 - -
1 0 0 -
3 1 0 0
4 0 2 0
5 0 0 3

转移方程

P(i,j) = P(i-1,j-1) + 1

代码

str_tmp = []
str_tmp << gets.strip
str_tmp << gets.strip 
str1 ,str2 = '', ''
if str_tmp.first.size < str_tmp.last.size 
    str1, str2 = str_tmp
else 
    str2, str1 = str_tmp
end
map = {}
str1.size.times{|i| map[i] = {}}

max_l = 0
str1.size.times do |i| 
   str2.size.times do |j|
       if str1[i] == str2[j]   
            if i-1 >= 0 && j-1 >=0
                map[i][j] = map[i-1][j-1]+1
            else 
                map[i][j] = 1
            end
           max_l = map[i][j] if map[i][j] > max_l
       else 
           map[i][j] = 0
       end
   end
end
puts max_l
全部评论

相关推荐

不要停下啊:大二打开牛客,你有机会开卷了,卷起来,去找课程学习,在牛客上看看大家面试笔试都需要会什么,岗位有什么需求就去学什么,努力的人就一定会有收获,这句话从来都经得起考验,像我现在大三了啥也不会,被迫强行考研,炼狱难度开局,啥也不会,找工作没希望了,考研有丝丝机会
点赞 评论 收藏
分享
05-19 15:21
已编辑
华南农业大学 Java
白火同学:你才沟通了200,说实话,北上广深杭这里面你连一座城市的互联网公司都没投满呢,更别说还有各种准一线二线城市了。等你沟通突破了三位数,还没结果再考虑转行的事吧。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务