如何以所有可能的方式将字符串拆分为长度最多为 3 的连续子字符串? [英] How to split a string into consecutive substrings of length at most 3 in all possible ways?

查看:31
本文介绍了如何以所有可能的方式将字符串拆分为长度最多为 3 的连续子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试取一个长度介于 1 和 10 之间的字符串,并输出将字符串分解为大小为 1、2 或 3 的连续子字符串的所有可能方式.例如:

I am trying to take a string, between length 1 and 10, and output all possible ways of breaking up the string into consecutive substrings that are of sizes 1, 2, or 3. For example:

输入:123456

将整数切成单个字符,然后继续查找组合.该代码将返回以下所有数组.

Slice the integer into individual characters, then proceed through to find combinations. The code would return all of the following arrays.

    [1, 2, 3, 4, 5, 6]  
    [12, 3, 4, 5, 6]  
    [1, 23, 4, 5, 6]  
    [1, 2, 34, 5, 6]  
    [1, 2, 3, 45, 6]  
    [1, 2, 3, 4, 56]  
    [12, 34, 5, 6]  
    [12, 3, 45, 6]  
    [12, 3, 4, 56]  
    [1, 23, 45, 6]  
    [1, 2, 34, 56]  
    [1, 23, 4, 56]  
    [12, 34, 56]  
    [123, 4, 5, 6]  
    [1, 234, 5, 6]  
    [1, 2, 345, 6]  
    [1, 2, 3, 456]  
    [123, 456]  
    [1, 23, 456]  
    [1, 234, 56]  
    [12, 345, 6]  
    [12, 3, 456]  
    [123, 4, 56]  
    [123, 45, 6]

我正在尝试用 ruby​​ 来做这件事.谢谢!

I'm trying to do this in ruby. Thanks!

推荐答案

这是一个工作函数.可能不是最佳选择,因为我没有花太多时间在上面.

Here's a working function. May be not optimal as I didn't spend much time on it.

str = "1234567890"

def f(s, n)
    return [[]] if s.empty?

    (1..[n, s.length].min).map{|c| f(s[c..-1], n).map{|a| [s[0, c]] + a}}.inject(&:+)
end

puts f(str, 3).collect{|l| l * "\t"}

将其缩短一点,长度现在作为第二个参数传递以实现灵活性.

Made it a bit shorter and the length is now passed as second parameter to function for flexibility.

这篇关于如何以所有可能的方式将字符串拆分为长度最多为 3 的连续子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆