链接到此问题:
https://www.hackerrank.com/contests/takneek/challenges/maximum-length-substring/problem
代码通过了初始测试用例,但是当我去黑客级别提交更大的字符串时,它超时了。我觉得这是我用于唯一子字符串的算法,如何将这段时间减少到有效的时间?
我的代码:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
LinkedList<Integer> kList = new LinkedList<Integer>();
LinkedList<String> setout = new LinkedList<String>();
LinkedList<String> setLex = new LinkedList<String>();
//Get the original text
String text = in.nextLine();
//Get n from the file
int n = in.nextInt();
//Get the next needed items for comparison and order
for (int i = 0; i < n; i++) {
kList.add(in.nextInt());
}
setout = getAllUniqueSubset(text);
setLex = sortLexographically(setout);
int findMax = findMaximumSub(setLex, kList, 0);
// System.out.println(setLex);
System.out.println(findMax);
}
//Get the unique subset to begin with and return it
public static LinkedList<String> getAllUniqueSubset(String text) {
LinkedList<String> set = new LinkedList<String>();
for (int i = 0; i < text.length(); i++) {
for (int j = 0; j < text.length() - i; j++) {
String elem =text.substring(j, j + (i+1));
if (!set.contains(elem)) {
set.add(elem);
}
}
}
return set;
}
public static LinkedList<String> sortLexographically(LinkedList<String> setout){
for(int i = 0; i < setout.size()-1; ++i) {
for (int j = i + 1; j < setout.size(); ++j) {
if (setout.get(i).compareTo(setout.get(j)) > 0) {
String testLex = setout.get(i);
setout.set(i, setout.get(j));
setout.set(j, testLex);
}
}
}
return setout;
}
public static int findMaximumSub(LinkedList<String> setLex, LinkedList<Integer> kList, int maxCheck){
for (int i = 0; i < kList.size()-1; i++) {
if (maxCheck < setLex.get(kList.get(i)).length()) {
maxCheck = setLex.get(kList.get(i)).length();
}
}
return maxCheck;
}
}