最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

生成字符串的所有可能的连续单词组合

SEO心得admin133浏览0评论
本文介绍了生成字符串的所有可能的连续单词组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想生成特定字符串的所有可能的连续单词组合,给定最小长度作为arg.

所以说我有"hello",结果将是(给定的最小长度为3):"hel","ell","llo","hell","ello","hello".

我实现此目标的一种方法是:

def get_all_word_combinations(str,min_length)字符= str.split('')all_results = [](min_length..str.size).每个| x |chars.each_cons(x)做| r |all_results<<加入结尾结尾返回all_results结尾

但是不确定这是否可以用较大的单词来表达.

解决方案

此解决方案避免了不必要的 joins :

word ="hello"大小= word.sizemin_size = 3(min_size..size).flat_map {| l |(0..size-l).map {| i |词[i,l]}}#=>["hel","ell","llo","hell","ello","hello"]

如果您不需要数组,而只需要遍历每个可能的子字符串,则此解决方案将使用更少的内存:

(min_size..size).each | l |(0..size-l).each做| i |#用单词[i,l]做点什么结尾结尾

I want to generate all possible consecutive word combinations of a particular string, given a minimum length as an arg.

So say I have "hello", the result would be (given a min length of 3): 'hel', 'ell', 'llo', 'hell', 'ello', 'hello'.

One way I've achieve this is via:

def get_all_word_combinations(str, min_length) chars = str.split('') all_results = [] (min_length..str.size).each do |x| chars.each_cons(x) do |r| all_results << r.join end end return all_results end

But not sure if this would work with bigger words.

解决方案

This solution avoids unnecessary joins :

word = "hello" size = word.size min_size = 3 (min_size..size).flat_map { |l| (0..size - l).map { |i| word[i, l] } } #=> ["hel", "ell", "llo", "hell", "ello", "hello"]

If you don't need an Array but just need to iterate over every possible substring, this solution will use less memory :

(min_size..size).each do |l| (0..size - l).each do |i| # do something with word[i, l] end end

发布评论

评论列表(0)

  1. 暂无评论