如何获得某个字符串中重复的所有字符的数值?

问题描述:

def num_repeats(string) 
    letters = string.chars 
    idx = 0 
    n = 1 
    arr = [] 
    lettercount = 0 
    while idx < letters.length 
     lettercount = 0 
     while n < letters.length 
      if letters[idx] == letters[n] 
       lettercount = 1 
      end 
      n+=1 
     end 
     if lettercount > 0 
      arr.push(idx) 
     end 
     idx += 1 
    end 
    return arr.length 
end 

puts(num_repeats("abdbccc")) 
# == 2 since 2 letters are repeated across the string of characters 

我一直收到0,虽然我看到它,如果重复一个数字,numbercount的值应该从零移到一个,然后允许一些值被推入数组,然后我得到所述数组的长度确定重复字符的数量。我的循环有问题吗?如何获得某个字符串中重复的所有字符的数值?

+0

我不明白你想要做什么。也许发布一些预期的输入/输出? – Adrian

+0

我希望这个评论澄清一点 – Chris

没明白你要做的,也许你可以使用哈希来帮助:

def num_repeats(string) 
    letters = string.chars 
    counter_hash = Hash.new(0) 
    letters.each { |l| counter_hash[l] += 1 } 
    counter_hash 
end 

UPDATE

如果你真的想用同一种代码算法做到这一点,那么这里是它的问题:

在你的第二个while循环中,变量n应该从idx+1开始,consid因此,您正在尝试提取索引,然后查找该索引处的字符是否在索引之后的某处重复。

但即使您修复,您将得到3abdbccc。这有点表明你的算法是错误的。当重复字符出现超过2次时,就像我在上面的段落中所说的过程一样,除了最后一个字符以外,您都会这样做,而不检查字符是否已被检测到重复。插图:

str = 'aaa' 
When idx = 0, you get str[idx] == str[n=1], adds it to the result. 
When idx = 1, you get str[idx] == str[n=2], adds it to the result. 

现在你计算了a两次重复。我想你可以单独解决这个问题。


我认为你只是试图做同样的,因为这(假设你需要检查只有小写字母):

str = "abdbccc" 
('a'..'z').count { |x| str.count(x) > 1 } 
# => 2 

或者,如果你需要检查重复的字符数任何字符:

str = "12233aabc" 
str.chars.group_by(&:to_s).count do |k, v| 
    v.size > 1 
end 
# => 3 

这是我们正在谈论的Ruby。在Ruby中编写这样的代码并不是一个好主意,我的意思是你使用了很多while循环并手动追踪它们的计数器,而在Ruby中,通常不必处理这些,考虑到所有方便,少Ruby提供的更容易出错和更短的替代方案。我认为你有一个类似C的背景,我建议你更多地学习Ruby和Ruby的做事方式。

你有这样的内环

while n < letters.length 
     if letters[idx] == letters[n] 
      lettercount = 1 
     end 
     n+=1 

但无处你重新n,所以这个循环已扫描一次后,它会跳过以后每一次

可以主要解决的是通过设置n到这里idx + 1

while idx < letters.length 
    lettercount = 0 
    n = idx + 1 
    while n < letters.length 

你仍然会得到结果,因为你没有检测到c已经算

你可以用一对夫妇解决这个最后的问题更多的调整

def num_repeats(string) 
    letters = string.chars 
    idx = 0 
    arr = [] 
    lettercount = 0 
    while idx < letters.length 
     lettercount = 0 
     n = idx + 1     # <== start looking after idx char 
     while n < letters.length 
      if letters[idx] == letters[n] 
       lettercount += 1 # <== incrementing here 
      end 
      n+=1 
     end 
     if lettercount == 1   # <== check for exactly one 
      arr.push(idx) 
     end 
     idx += 1 
    end 
    return arr.length 
end 

这工作,因为现在lettercount == 2第一个c如此重复不计,直到你得到第二个c其中lettercount == 1

这仍然被认为是一个糟糕的解决方案,因为它具有O(n ** 2)的复杂性。有解决方案 - 例如使用Hash哪些是O(n)