按大小顺序打印给定字符串的所有子字符串

Print all the substrings of a given string in order by size

这个问题已经被询问和回答了很多次,但我特别要求按尺寸从大到小列出订单。

public static void main(String[] args)
{
    String inputedWord = "ABIGWORD";

    for (String str : breakStringIntoPieces(inputedWord, 2))
    {
        System.out.print("\n") + str;
    }
}

                                                            //Pass in word and minimum
                                                            //substring length to print
public static List<String> breakStringIntoAllPossibleSubstrings(String str, int num)
{                                                               
    List<String> listOfSubstrings = new ArrayList<>();
    Boolean insideLoop = false;

    for(int i=0; i<=str.length()-num; i++)
    {
        for(int j=str.length(); j>=i+num; j--)
        {
            //System.out.println(str.substring(i, j));
            if (insideLoop) //This is simply to not add the complete string to the 
            {               //list. Only substrings

                listOfSubstrings.add(str.substring(i, j));
            }
            insideLoop = true;
        }
    }
    return listOfSubstrings;
}

输出:

ABIGWOR
ABIGWO
ABIGW
ABIG
ABI
AB

BIGWORD
BIGWOR
BIGWO
BIGW
BIG
BI

IGWORD
IGWOR
IGWO
IGW
IG

GWORD
GWOR
GWO
GW

WORD
WOR
WO

ORD
OR

RD

DESIRED OUTPUT:(除尺寸外没有特殊顺序。这只是一个打字示例。

ABIGWOR
BIGWORD
ABIGWO
BIGWOR
IGWORD
GWORD
ABIGW
IGWOR
BIGWO
IGWO
ABIG
BIGW
WORD
GWOR
GWO
ORD
ABI
BIG
IGW
WOR
AB
BI
IG
GW
WO
OR
RD

从技术上讲,我可以循环遍历返回的列表并找到所有最大的子字符串,但这会增加太多步骤。我想知道是否可以在给定的方法中完成它。我认为这个过程涉及在每个循环之后操纵 i 和 j 迭代器?

实现此目的的一种简单方法,只需进行最少的更改,即按长度对 listOfSubstrings ArrayList 进行排序,然后对结果进行 return 排序。这只是使用 Collections.sort.

的一行更改
public static List<String> breakStringIntoAllPossibleSubstrings(String str, int num) {                                                               
    List<String> listOfSubstrings = new ArrayList<>();

    /* Your code added here... */

    // This will sort in descending order of length
    Collections.sort(listOfSubstrings, (item1, item2) -> item2.length() - item1.length());

    return listOfSubstrings;
}

就时间复杂度而言,对于大小为N的String,生成所有子串的顺序为O(N^2)

额外的排序操作将引入 O(N^2 x log(N^2)) = O(N^2 x log(N))

因此,整体复杂度将为 O(N^2 x log(N))