在给定限制的字符串中查找唯一的子字符串

时间:2019-05-25 17:59:20

标签: java

给定字符串s,对于给定长度k,生成一组所有唯一子字符串的java程序是什么?

示例:对于str =“ abdd”,对于k = 2,我们将获得substrs = {“ ab”,“ ad”,“ ba”,“ bd”,“ da”,“ db”}

import java.util.*;

public class UniqueSubStringInString {
public static void main(String[] args) {
    findUniqueSubStringInString("abdd", 2);
}

public static void findUniqueSubStringInString(String s, int k) {
    char[] letters = s.toCharArray();
    Set<Character> uniques = new LinkedHashSet<Character>();
    for (int i = 0; i < letters.length; i++) {
        uniques.add(letters[i]);
    }
    Character[] array = uniques.toArray(new Character[uniques.size()]);
    List<List<Character>> permList = permute(array, k);
    List<String> finalList = new ArrayList<String>();
    for (List<Character> list : permList) {
        StringBuilder builder = new StringBuilder();
        for (Character ch : list) {
            builder.append(ch);
        }
        finalList.add(builder.toString());
    }
    String[] finalStrArray = finalList.toArray(new String[finalList.size()]);
    for (String str : finalStrArray) {
        System.out.println(str);
    }
}

public static List<List<Character>> permute(Character[] charArray, int k) {
    List<List<Character>> results = new ArrayList<List<Character>>();
    backtrack(results, new ArrayList<Character>(), charArray, k);
    return results;
}

private static void backtrack(List<List<Character>> list, List<Character> tempList, Character[] charArray, int k) {
    if (tempList.size() == k) {
        list.add(new ArrayList<>(tempList));
    } else {
        for (int i = 0; i < charArray.length; i++) {
            if (tempList.contains(charArray[i]))
                continue;
            tempList.add(charArray[i]);
            backtrack(list, tempList, charArray, k);
            tempList.remove(tempList.size() - 1);
        }
    }
}
}

请告诉我该程序是否可以进一步优化。

0 个答案:

没有答案