ruby - Ruby 将一长串字符拆分为实际单词
问题描述
我有一个包含 2 个元素的字符串数组:第一个是字符序列,第二个是一长串以逗号分隔的单词,按字母顺序表示任意长度的字典。现在我想检查是否可以从第二个元素的单词列表中创建数组中第一个元素的单词。
下面的例子将更好地说明我的意思:
string_array = ["baseball", "a,all,b,ball,bas,base,cat,code,d,e,quit,z"]
Output: base,ball
所以我做的是简单的方法:
def word_split(string_array)
splitted_arr = string_array[1].split(',')
strArr.include?(splitted_arr)
end
但它只给了我false
结果。如何比较数组中的那些字符串?
解决方案
我做了一个带有两个参数的方法:一个单词和一个单词数组。如果需要,您可以轻松地创建一个对您建议的数据结构进行操作的包装函数。
def find_sequence(target, words)
return [] if target.empty?
words.each do |word|
if target.start_with?(word)
# We found a good candidate for the first word, so let's recurse
# and see if we can find the rest of the words.
remainder = target.sub(word, '') # remove word from start of target
seq = find_sequence(remainder, words)
return [word] + seq if seq
end
end
nil
end
# Example 1: your example
s = ["baseball", "a,all,b,ball,bas,base,cat,code,d,e,quit,z"]
p find_sequence(s[0], s[1].split(",")) # ["bas", "e", "b", "all"]
# Example 2: no solution
p find_sequence("foobar", ["foo", "cat"]) # nil
# Example 3: backtracking
p find_sequence("abcde", ["abcd","abc","ab","a","d","bcde"]) # ["a", "bcde"]
顺便说一下,这是深度优先搜索的一个例子。
推荐阅读
- ibm-cloud - 将 CLI 用于具有 IAM 命名空间的云功能时出错
- batch-file - 获取早于 x 天的空文件夹列表
- java - 您可以在每次单击按钮时随机生成一个 JPanel 吗?
- azure - SignalR 核心:启用 Web 套接字并将 Azure 应用服务扩展到多个实例时是否需要 ARR 关联?
- javascript - 使用属性 table-layout:fixed 在表格中调整窗口大小时更改宽度
- javascript - Redux 调度可能会改变的情况有哪些?
- android - 在跨度中隐藏字符串内容
- schema.org - “您的附加链接搜索框模板中存在错误:INVALID_SYNTAX”
- python - 为什么我得到索引 0 超出了轴 0 大小为 0 的范围?
- javascript - 如何以动态方式控制带有悬停(显示和隐藏)的元素