ITeye博客

寻找最长递增数字子串

googya · 2010-10-17 18:55 · JRuby&Ruby · 编程语言 · Markdown

有一个字符串,其中包含了多个数字子串,要求求出最长的递增数字子串,比如,s='asdf1123as456df112365asdfa'中最长递增数字子串是11236.



string="asdfasdfasdf1111112222222356789462124asdfasdfasdfa9874563214756asdfasdfasdfasdfasdfasdfalkjlaskdjflkasdf124578"
s=string.scan(/\d+/)
#t=s[1].split //
#puts t.size
#print t,"\n"
ss=[]
hash={}
max=tt=0
s.each do |t|
    t=t.split //
for i in 0...(t.size)
    if(t[i+1]&&t[i+1]>=t[i])
         ss<<t[i]
        tt+=1
        if(tt>max)
            max=tt
            hash[ss.join('')]=max
        end
    else
        ss<<t[i]
        hash[ss.join('')]=ss.size
        ss=[]
        tt=0
    end
end
end
puts  hash.sort_by {|k,v|k.size}.last[0]
#puts hash


应该会有更简洁的方法的,慢慢再想!!!!

评论(14)

  1. #14 楼 · orcl_zhang · 2010-10-18 22:01

    Hooopo writes:

    :x :x :x :x

    虎跑看傻了.

  2. #13 楼 · Hooopo · 2010-10-18 20:54

    :x :x :x :x

  3. #12 楼 · orcl_zhang · 2010-10-18 17:23

    googya writes:

    [quote=night_stalker][code=ruby]"aaa31e4r23r".scan(/0123456789/).max_by(&:size)[/code][/quote]

    高招!!!!

    ns太猛了.. :idea: :idea:

  4. #11 楼 · googya · 2010-10-18 16:09

    正则表达式果然很强大!

  5. #10 楼 · googya · 2010-10-18 15:51

    night_stalker writes:

    [code=ruby]"aaa31e4r23r".scan(/0123456789/).max_by(&:size)[/code]

    高招!!!!

  6. #9 楼 · night_stalker · 2010-10-18 15:36
    "aaa31e4r23r".scan(/0*1*2*3*4*5*6*7*8*9*/).max_by(&:size)
    
  7. #8 楼 · orcl_zhang · 2010-10-18 00:23

    首先用正则找到数字字符串

    "aaa31e4r23r".split(/\D+/)
    

    在用collect调用下面的方法,找到每个数字字符串中最长递增数字子串. 找出数字字符串中最长递增数字子串.

    
    t = "238923".chars.to_a
    result = []
    temp = ""
    
    while !t.empty? do
      temp << t[0] if temp.empty?
      if t[1]
         t[0] <= t[1] ? temp << t[1] : (result << temp;temp = "")
      else
        result << temp
      end
      t.shift
    end
    
    puts result.join(',')
    
    

    然后在冒泡,找到size最长的.

  8. #7 楼 · googya · 2010-10-17 21:30

    orcl_zhang writes:

    [quote]寻找最长递增数字子串[/quote] 提交完后,悲剧的发现看错题目了....

    要不要我帮你删除掉? :D

  9. #6 楼 · orcl_zhang · 2010-10-17 21:25

    寻找最长递增数字子串

    提交完后,悲剧的发现看错题目了....

  10. #5 楼 · googya · 2010-10-17 21:25

    orcl_zhang writes:

    没有必要排序的,求出最大即可. :lol:

    不好意思这位哥们,是求最长递增数字子串,我刚开始没有说清楚(虽然我代码已经写清楚了)

  11. #4 楼 · orcl_zhang · 2010-10-17 21:20

    没有必要排序的,求出最大即可. :lol:

  12. #3 楼 · orcl_zhang · 2010-10-17 21:19

    lz你代码真的很无语... s.each do |t|
    t=t.split //这里t.size == 1吧,你要干吗..... for i in 0...(t.size)
    if(t&&t>=t*) //这一陀是干吗的.. ss<<t*
    hash=ss.size
    ss=
    tt=0

    盗用hooopo的代码,修改下.

    "aaa31e4r23r".split(/\D+/).collect(&:size).max
    
  13. #2 楼 · googya · 2010-10-17 21:16

    Hooopo writes:

    [code=ruby]"aaa31e4r23r".split(/\D+/).sort_by{|x| x.size}.last [/code]

    虎跑,不好意思啊,是求最长递增数字子串。当时写掉了这个要求!!! :oops: :oops:

  14. #1 楼 · Hooopo · 2010-10-17 20:40
    "aaa31e4r23r".split(/\D+/).sort_by{|x| x.size}.last                  
    

评论功能维护中,当前仅展示历史评论。