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

编程入门 行业动态 更新时间:2024-10-08 00:28:01
本文介绍了生成字符串的所有可能的连续单词组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想生成特定字符串的所有可能的连续单词组合,给定最小长度作为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

更多推荐

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

本文发布于:2023-11-30 07:33:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649184.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   字符串   单词

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!