cucugbgb 发表于 2010-11-01 13:07

寻找最长递增数字子串

有一个字符串,其中包含了多个数字子串,要求求出最长的递增数字子串,比如,s='asdf1123as456df112365asdfa'中最长递增数字子串是11236.
string="asdfasdfasdf1111112222222356789462124asdfasdfasdfa9874563214756asdfasdfasdfasdfasdfasdfalkjlaskdjflkasdf124578"
s=string.scan(/\d+/)
#t=s.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&&t>=t)
         ss<<t
      tt+=1
      if(tt>max)
            max=tt
            hash=max
      end
    else
      ss<<t
      hash=ss.size
      ss=[]
      tt=0
    end
end
end
putshash.sort_by {|k,v|k.size}.last
#puts hash应该会有更简洁的方法的。

fiyuer 发表于 2010-11-11 22:34

本帖最后由 fiyuer 于 2010-11-11 23:37 编辑

str = 'asdf1123as4567889999df112365asdfa'
bytes = str.bytes.to_a
w = []
bytes.each_with_index do |cur, index|
   if cur > '9'.ord or cur < '0'.ord
          w = 0
   else
          if index ==0 or w== 0 or cur < bytes
                w = 1
          else
                w = w + 1
          end
   end
end
str
页: [1]
查看完整版本: 寻找最长递增数字子串