pangram是一个包含字母表中每一个字母至少一次的句子。例如,“飞快的棕色狐狸跳过懒狗”这个句子是一个庞加姆,因为它至少使用一次字母A(大小写无关)。我正在尝试创建一个方法,它接受一个字符串并返回true或false,如果它是pangram的话。这就是我到目前为止尝试过的。
def pangram?(string)
letters = string.chars.downcase.uniq
letters.uniq.all? {|c| string.count(c)==26}
end
def pangram?(string)
string.downcase
("a".."z").all?{|c| string.count(c) <= 1}
end
有更好的建议吗?提前感谢!
发布于 2021-01-21 17:01:56
你可以做这样的事情:
s.downcase.scan(/[a-z]/).uniq.size == 26
这将减少字符串扫描所有字符"a“到"z”,并检查这些字符的uniq大小是否等于26。
当前解决方案的问题
第一个永远不会像现在这样工作
chars
返回一个Array
,而Array#downcase
不是一个方法string.count(c)==26
),因此'a' * 26
将通过这个测试,但是“快速的棕色狐狸跳过懒惰的狗”不会。第二个问题也有:
,
String#count
处理为inefficient;''
,将通过此测试。例如:<= 1
times.发布于 2021-01-21 17:34:09
def pangram?(string)
(("a".."z").to_a - string.downcase.chars).empty?
end
发布于 2021-01-21 19:01:14
require 'set'
def pangram?(str)
str.downcase.each_char.with_object(('a'..'z').to_set) {|c,st| st.delete(c)}.empty?
end
pangram?("The quick brown dog jumps over the lazy fox") #=> true
pangram?("The quick brown dog jumps over the lazy fo.") #=> false
pangram?("The quick brown dog, Saffi, jumps over the lazy fox.") #=> true
我已经将'a'..'z'
转换成一个集合,而不仅仅是为了加速计算。
如果字符串是长的,那么一旦找到26个不同的字符,返回true
可能会更快:
def pangram?(str)
str.downcase.each_char.with_object(('a'..'z').to_set) do |c,st|
st.delete(c)
return true if s.empty?
end
false
end
https://stackoverflow.com/questions/65831749
复制相似问题