Ruby字符串编码 连续字母频率

3
我想在Ruby中对字符串进行编码,使输出成对出现以便我能够解码。我希望以这种方式进行编码,即每对包含字符串中下一个不同的字母和连续重复的数量。
例如,如果我编码“aaabbcbbaaa”,输出应该是[["a", 3], ["b", 2], ["c", 1], ["b", 2], ["a", 3]]。
以下是代码。
def encode( s )
    b = 0
    e = s.length - 1
    ret = [] 
    while ( s <= e )
        m = s.match( /(\w)\1*/ )
        l = m[0][0]
        n = m[0].length
        ret << [l, n]
    end
    ret
end

5
你尝试过为此编写任何代码吗?如果是这样,你的代码是什么样子的? - summea
def encode( s ) b = 0 e = s.length - 1 ret = [] while ( s <= e ) m = s.match( /(\w)\1*/ ) l = m[0][0] n = m[0].length ret << [l, n] end ret end - Haris Ali
1
@HarisAli请将您尝试的代码放在您的帖子描述中。 - Arup Rakshit
4个回答

8
"aaabbcbbaaa".chars.chunk{|i| i}.map{|m,n| [m,n.count(m)]}
#=> [["a", 3], ["b", 2], ["c", 1], ["b", 2], ["a", 3]]

5
"aaabbcbbaaa".scan(/((.)\2*)/).map{|s, c| [c, s.length]}

啊哈,解构参数赋值,不错。 - DigitalRoss

4
您还可以使用程序方法来完成此操作。
def group_consecutive(input)
  groups = []
  input.each_char do |c|
    if groups.empty? || groups.last[0] != c
      groups << [c, 1]
    else
      groups.last[1] += 1
    end
  end
  groups
end

1
'aaabbcbbaaa'.scan(/((.)\2*)/).map {|e| [e[1], e[0].size]}

我们想出了相似的想法,这表明我们在正确的路线上。 - sawa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接