java - Hackerrank (Java) MAXIMUM LENGTH SUBSTRING - 超时错误
问题描述
链接到这个问题:
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;
}
}
解决方案
推荐阅读
- kubernetes - terraform 中“kubernetes apply -k”的等价物是什么?
- python - 为特定功能设置超时时间
- azure - Azure 数据工厂 ADF 数据管道将文件名包含在将数据复制到 sql 数据库中
- python - 使用 Google Sheets API,我可以使用 get 方法从表中获取数据,但 append 方法会出错
- mysql - SQL中具有相同日期的不同值
- ios - Json字符串转换
- java - Gson如何序列化和反序列化Lombok生成的继承POJO?
- html - 如何在 Angular 中将代码的某些 HTML 部分预览为 PDF 或 DOCX 文件
- r - 无法选择已在 Shiny R 中选择的菜单项
- machine-learning - 有没有好的开源图像数据集生成软件?