繁体   English   中英

将字符串拆分为“N”个大致相等的部分(Java)

[英]Split a String into 'N' Roughly Equal Pieces (Java)

我问的问题已在此处提出/回答,但是提供的答案使用 Python 特定库,因此无济于事。

我正在尝试构建一个算法,给出:

  • 长度为l的字符串s
  • 多个“分裂” n

将返回n个子字符串ss ,其长度ssl彼此之间的距离不能超过 1。


例子:

ATestString拆分为 3 个部分:

  • 以下是有效的: ["ates", "tstr", "ing"] , [4, 4, 3]
  • 而这不会: ["atest", "strin", "g"] , [5, 4, 1]

AnotherTestString拆分为 4 个部分:

  • 有效: ["Anoth", "erTe", "stSt", "ring"] , [5, 4, 4, 4,]
static int[] PerformStringDivision(String word, int numSplits) {

    int len = word.length();;
    int[] solution = new int[numSplits]; // an array of strings that will hold the solution

    int roughDivision = (int) Math.ceil( (double) len/numSplits); // the length of each divided word
    int remainingLetters = len;
    
    boolean reduced = false; // flag to see if I've already reduced the size of the sub-words
    
    for (int i = 0; i < numSplits; ++i) {

        
        int x = (roughDivision-1)*(numSplits-(i)); // see next comment
        // checks to see if a reduced word length * remaining splits exactly equals remaining letters
        if (!reduced && x == remainingLetters) {
            roughDivision -= 1;
            reduced = true;
        }

        solution[i] = roughDivision;

        remainingLetters -= roughDivision;
    }

    return solution;
}

继续评估您可以在循环的每次迭代中从字符串中提取的最大字符数,基于:

  1. 字符串中的剩余字符
  2. 处理整个字符串的剩余循环数

就像是:

public class Main
{
    public static void main(String[] args) throws Exception
    {
        String text = "ALongerTestString";
        int parts = 4;

        String[] result = Main.split(text, parts);
        System.out.println( Arrays.asList( result ) );
    }

    static public String[] split(String text, int parts)
    {
        String[] list = new String[parts];
        double length = (double)text.length();

        int start = 0;

        for (int i = 0; i < parts; i++)
        {
            double remainder = length - start;
            int characters = (int)Math.ceil(remainder / (parts - i));
            int end = start + characters;
            list[i] = text.substring(start, end);
            start = end;
        }

        return list;
    }
}

第一个str.length() % n子字符串需要长 1 个字符。

一种可能的解决方案是:

public static List<String> divide(String s, int n) {
    List<String> result = new ArrayList<>();
    int len = s.length() / n;
    int rem = s.length() % n;
    for (int i = 0, pos = 0; i < n; i++) {
        int end = pos + len + (rem-- > 0 ? 1: 0);
        result.add(s.substring(pos, end));
        pos = end;
    }
    return result;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM