免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2627 | 回复: 1
打印 上一主题 下一主题

寻找最长递增数字子串 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-11-01 13:07 |只看该作者 |倒序浏览
有一个字符串,其中包含了多个数字子串,要求求出最长的递增数字子串,比如,s='asdf1123as456df112365asdfa'中最长递增数字子串是11236.

  1. string="asdfasdfasdf1111112222222356789462124asdfasdfasdfa9874563214756asdfasdfasdfasdfasdfasdfalkjlaskdjflkasdf124578"
  2. s=string.scan(/\d+/)
  3. #t=s[1].split //
  4. #puts t.size
  5. #print t,"\n"
  6. ss=[]
  7. hash={}
  8. max=tt=0
  9. s.each do |t|
  10.     t=t.split //
  11. for i in 0...(t.size)
  12.     if(t[i+1]&&t[i+1]>=t[i])
  13.          ss<<t[i]
  14.         tt+=1
  15.         if(tt>max)
  16.             max=tt
  17.             hash[ss.join('')]=max
  18.         end
  19.     else
  20.         ss<<t[i]
  21.         hash[ss.join('')]=ss.size
  22.         ss=[]
  23.         tt=0
  24.     end
  25. end
  26. end
  27. puts  hash.sort_by {|k,v|k.size}.last[0]
  28. #puts hash
复制代码
应该会有更简洁的方法的。

论坛徽章:
0
2 [报告]
发表于 2010-11-11 22:34 |只看该作者
本帖最后由 fiyuer 于 2010-11-11 23:37 编辑
  1. str = 'asdf1123as4567889999df112365asdfa'
  2. bytes = str.bytes.to_a
  3. w = []
  4. bytes.each_with_index do |cur, index|
  5.      if cur > '9'.ord or cur < '0'.ord
  6.           w[index] = 0
  7.      else
  8.           if index ==0 or w[index - 1]  == 0 or cur < bytes[index - 1]
  9.                 w[index] = 1
  10.           else
  11.                 w[index] = w[index - 1] + 1
  12.           end
  13.      end
  14. end
  15. str[w.index(w.max) - w.max + 1, w.max]
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP