假设我有一个字符串,例如string= "aasmflathesorcerersnstonedksaottersapldrrysaahf"
。如果您没有注意到,则可以"harry potter and the sorcerers stone"
在其中找到短语(减去空格)。
我需要检查是否string
包含字符串的所有元素。
string.include? ("sorcerer") #=> true
string.include? ("harrypotterandtheasorcerersstone") #=> false, even though it contains all the letters to spell harrypotterandthesorcerersstone
包含不适用于改组后的字符串。
如何检查一个字符串是否包含另一个字符串的所有元素?
集合和数组的交集不考虑重复的字符,但是直方图/频率计数器可以:
require 'facets'
s1 = "aasmflathesorcerersnstonedksaottersapldrrysaahf"
s2 = "harrypotterandtheasorcerersstone"
freq1 = s1.chars.frequency
freq2 = s2.chars.frequency
freq2.all? { |char2, count2| freq1[char2] >= count2 }
#=> true
Array#frequency
如果您不想使用方面方面的内容,请编写自己的内容。
class Array
def frequency
Hash.new(0).tap { |counts| each { |v| counts[v] += 1 } }
end
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句