请解释这个返回重复字母数的Ruby方法

时间:2014-10-21 05:03:18

标签: ruby

任何人都可以解释一下这段代码吗?我不明白具体:

  elsif idx2 > idx1
    is_repeat = true
  end
  1. 为什么我们要比较指数以确定是否有信件 重复?
  2. if语句中的“下一个”术语是做什么的?
  3. 完整代码如下所示:

    # Write a method that takes in a string and returns the number of
    # letters that appear more than once in the string. You may assume
    # the string contains only lowercase letters. Count the number of
    # letters that repeat, not the number of times they repeat in the
    # string.
    #
    # Difficulty: hard.
    
    def num_repeats(array)
      repeats = 0
    
      idx1 = 0
      while idx1 < array.length
        is_repeat = false
        idx2 = 0
        while idx2 < array.length
          if array[idx1] != array[idx2]
            idx2 += 1
            next
          elsif idx2 < idx1
            # will have previously counted this repeat
            break
          elsif idx2 > idx1
            is_repeat = true
          end
    
          idx2 += 1
        end
    
        if is_repeat
          repeats += 1
        end
    
        idx1 += 1
      end
    
      return repeats
    end
    

1 个答案:

答案 0 :(得分:1)

如果之前的条件(if idx2 < array.lengthelsif idx2 < idx1)都是falseidx2 > idx1true,那么将局部变量is_repeat设置为true ...