首页 > 解决方案 > 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结果。如何比较数组中的那些字符串?

标签: ruby

解决方案


我做了一个带有两个参数的方法:一个单词和一个单词数组。如果需要,您可以轻松地创建一个对您建议的数据结构进行操作的包装函数。

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"]

顺便说一下,这是深度优先搜索的一个例子。


推荐阅读