首页 > 解决方案 > 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; 
}    

}

标签: javaperformance

解决方案


推荐阅读