字符串数组中的子字符串数组 [英] array of substrings in array of strings
本文介绍了字符串数组中的子字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个字符串数组。一个数组中的字符串可能是另一数组中的字符串子集。我需要找出一个数组中的所有字符串是另一个数组中的字符串的子字符串
I have two array of strings. Strings in one array might be the subset of string in other array. I need to find out which all strings in one array are the substrings of strings in the other array
示例:
arr1 = ["firestorm", "peanut", "earthworm"]
arr2 = ["fire", "tree", "worm", "rest"]
结果:
res = ["fire","worm", "rest"]
我的解决方案在下面提到。但是需要很多时间。我必须处理成千上万的单词。
My solution is mentioned below. But it takes a lot of time. I have to process Thousands of words.
解决方案:
res =[]
arr1.each do |word1|
arr2.each do |word2|
if word1.include? word2
res << word2
end
end
end
请建议我更快
推荐答案
不幸的是,我们不知道您的解决方案。
Unfortunely we don't know your solution.
但是Array比String占用更多的内存空间。因此,您可以对其进行转换。
But Array takes up more memory space than String. So you can convert it.
arr1 = ["firestorm", "peanut", "earthworm"]
arr2 = ["fire", "tree", "worm", "rest"]
arr1 = arr1.join(',')
然后
res = arr2.select { |word| arr1.include?(word) } #=> ["fire", "worm", "rest"]
或
res = arr2.select { |word| arr1.match?(word) } #=> ["fire", "worm", "rest"]
或
res = arr2.select { |word| arr1.match(word) } #=> ["fire", "worm", "rest"]
这篇关于字符串数组中的子字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文