Skip to content

Instantly share code, notes, and snippets.

@javajosh
Created October 27, 2017 18:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save javajosh/49197a9e496a485edfb819ae6f6e178a to your computer and use it in GitHub Desktop.
Save javajosh/49197a9e496a485edfb819ae6f6e178a to your computer and use it in GitHub Desktop.
import java.io.*;
import java.util.*;
public class Substrings {
static boolean DEBUG = false;
static Set<String> substrings(String source){
Set<String> substrings = new TreeSet<>();
for (int i = 0; i < source.length(); i++) {
for (int j = i + 1; j <= source.length(); j++) {
substrings.add(source.substring(i, j));
}
}
return substrings;
}
static String concat(Collection<String> strings){
StringBuilder sb = new StringBuilder();
for (String string: strings){
sb.append(string);
}
return sb.toString();
}
static char test(String source, long elt){
Set<String> substrings = substrings(source);
if (DEBUG) System.out.println(substrings);
long count = 0;
for(String string: substrings){
count += string.length();
if (count < elt){
continue;
} else if (count == elt){
return string.charAt(string.length() - 1);
} else if (count > elt) {
return string.charAt((int)(count - elt));
}
}
throw new RuntimeException("Requested element is too big " + elt + ", " + count);
}
public static void main(String[] args) throws FileNotFoundException {
if (args.length > 0){
String fileName = args[0];
System.out.println("Reading input from file " + fileName);
System.setIn(new FileInputStream(new File(fileName)));
}
System.out.println(test("dbac",3));
Scanner s = new Scanner(System.in);
int numTests = s.nextInt();
String source;
int k;
while(numTests-- > 0){
source = s.next();
k = s.nextInt() - 1; //Compensate for 1-based input
System.out.println(test(source, k));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment