class Yukicoder def initialize t = gets.to_i @cache_good = Hash.new @cache_problem = Hash.new t.times do s = gets.chomp size = s.size min_dist = Float::INFINITY 0.upto(size - 7) do |i| dist1 = calc_dist_good(s[i..i+3]) (i+4).upto(size - 7) do |j| dist2 = calc_dist_problem(s[j..j+6]) min_dist = [min_dist, dist1 + dist2].min end end puts min_dist end end def calc_dist_good(str) return @cache_good[str] if @cache_good[str] dist = 0 0.upto(3) do |index| dist += 1 if str[index] != 'good'[index] end @cache_good[str] = dist end def calc_dist_problem(str) return @cache_problem[str] if @cache_problem[str] dist = 0 0.upto(6) do |index| dist += 1 if str[index] != 'problem'[index] end @cache_problem[str] = dist end end Yukicoder.new