mirror of
https://gitlab.com/mfocko/CodeWars.git
synced 2024-11-08 18:49:07 +01:00
42 lines
1 KiB
Java
42 lines
1 KiB
Java
class LongestConsec {
|
|
public static String longestConsec(String[] strarr, int k) {
|
|
int n = strarr.length;
|
|
|
|
// handle limits
|
|
if (n == 0 || k <= 0 || k > n) {
|
|
return "";
|
|
}
|
|
|
|
// determine lengths
|
|
int[] lengths = new int[n];
|
|
for (int i = 0; i < n; i++) {
|
|
lengths[i] = strarr[i].length();
|
|
}
|
|
|
|
// calculate first index
|
|
int maxIndex = 0, maxLength = 0;
|
|
for (int i = 0; i < k; i++) {
|
|
maxLength += lengths[i];
|
|
}
|
|
|
|
// Check rest of the array
|
|
int tmpLength = maxLength;
|
|
for (int i = 1; i < n - k + 1; i++) {
|
|
tmpLength += lengths[i + k - 1];
|
|
tmpLength -= lengths[i - 1];
|
|
|
|
if (tmpLength > maxLength) {
|
|
maxIndex = i;
|
|
maxLength = tmpLength;
|
|
}
|
|
}
|
|
|
|
// Join the strings
|
|
String result = "";
|
|
for (int i = maxIndex; i < maxIndex + k; i++) {
|
|
result += strarr[i];
|
|
}
|
|
|
|
return result;
|
|
}
|
|
}
|