(Ruby)方法检查元素是否已出现
我正在尝试编写一个方法,检查我们是否在字符串中多次看到元素。这段代码返回的是字符串,但不是布尔值——我认为它甚至没有返回正确的字符串 有人能提供建议吗(Ruby)方法检查元素是否已出现,ruby,Ruby,我正在尝试编写一个方法,检查我们是否在字符串中多次看到元素。这段代码返回的是字符串,但不是布尔值——我认为它甚至没有返回正确的字符串 有人能提供建议吗 def repeating_letters?(str) # downcase the whole str # create a "seen letters" array # iterate through each char in array # if seen letters contains that character, r
def repeating_letters?(str)
# downcase the whole str
# create a "seen letters" array
# iterate through each char in array
# if seen letters contains that character, return true
down = str.downcase
seen = []
down.each_char do |index|
if seen.include?(index)
TRUE
else
seen << index
end
end
end
p repeating_letters?("aA")
def重复字母?(str)
#把整条街道都拆了
#创建“可见字母”数组
#遍历数组中的每个字符
#如果看到包含该字符的字母,则返回true
down=str.downcase
SEED=[]
down.each|char do|索引|
如有。包括?(索引)
真的
其他的
你的代码中的问题是你浪费了你的true
,顺便说一句,你没有使用它。现在还不清楚你想做什么。我本以为看到的是一个散列,以防万一
def repeating_letters?(str)
str.downcase.chars.group_by(&:itself).values.any? { |a| a.size > 1 }
end
本身
可从Ruby 2.3.0获得,否则
def repeating_letters?(str)
str.downcase.chars.group_by { |c| c }.values.any? { |a| a.size > 1 }
end
你可以做:
def check(str)
repeated = false
str.downcase.split.uniq.each { |i| repeated = true and break if str.count(i) > 1 }
repeated
end
输出
> p repeating?("peEterr")
{"e"=>3, "a"=>2}
您可以更轻松地执行此操作:
def repeated_characters?(s)
!! s =~ /(.)\1/
end
没有数组,没有字符串循环,没有计数,只有一个简单的正则表达式,它匹配后跟相同字符的任何字符
或者,如果您不关心相邻关系,可以这样做:
Set.new(s.chars).length == s.length
# or this:
s.each_char.uniq.length == s.length
您的代码不起作用,因为返回接收方,即字符串。您必须使用显式的返回(我也解决了一些小问题)
这可以通过使用散列来计数字符来缩短:
def repeating_letters?(str)
seen = Hash.new(0)
str.downcase.each_char.any? { |char| (seen[char] += 1) == 2 }
end
在块中,char
的散列值增加1,并与2
进行比较,这表明之前是否看到过该char
我还将downcase
从方法移动到调用方,以使代码更加通用:
def repeating_letters?(str)
seen = Hash.new(0)
str.each_char.any? { |char| (seen[char] += 1) == 2 }
end
repeating_letters?('aA'.downcase)
是否应重复字母?(“aA”)
返回真
或假
?用对象(Hash.new(0))str.each字符。有吗?{| c,h | h[c]+=1;h[c]==2}
这个问题是重复问题的重复。公平地说,被接受的答案是低效的。带有捕获组和反向引用的正则表达式不是意味着数组、循环和计数吗?;-)@Stefan如果你想担心Oniguruma的实现细节,那就请便吧,但是没有……一个反向参考正在查看上一场比赛。这是一个窗口扫描操作。如果重复的字符必须彼此相邻(我不认为是这种情况,部分来自问题的标题),另一种方法是s.squence==s
。据我所知,问题中似乎没有任何东西表明只考虑相邻的重复字符。不过,第二种方法应该可以工作。不幸的是,代码必须先处理字符串中的每个字符,然后才能检测到重复字符。您可以使用lazy
:这在长字符串上非常缓慢,值得一提。如果您想获得每个字符的计数,最好使用上一个方法。上一个方法很短,可读性强,应该尽快返回。
def repeating_letters?(str)
seen = []
str.downcase.each_char.any? do |char|
if seen.include?(char)
true
else
seen << char
false
end
end
end
def repeating_letters?(str)
seen = Hash.new(0)
str.downcase.each_char.any? { |char| (seen[char] += 1) == 2 }
end
def repeating_letters?(str)
seen = Hash.new(0)
str.each_char.any? { |char| (seen[char] += 1) == 2 }
end
repeating_letters?('aA'.downcase)