0
0

More than 5 years have passed since last update.

文字の連続する数を使って基本的な文字列圧縮を行うメソッドを実装してください

Last updated at Posted at 2016-06-19

Chapter1 1.5

計算量O(n)のつもり

compress.rb
class String
  def compress
    temp_v = ""
    temp_arr = []
    count = 1
    for s in 0..self.length
      if s == 0
        temp_v = self[s]
        next
      else
        if temp_v == self[s]
          count += 1
        else
          temp_arr << temp_v + count.to_s
          temp_v = self[s]
          count = 1
        end
      end
    end

    if temp_arr.join.length == self.length
      self
    else
      temp_arr.join
    end
  end
end

str = "abbabcccccaaa"
puts str.compress
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0