Given an array of strings, return another array containing all of its longest strings.
Example
For inputArray = ["aba", "aa", "ad", "vcd", "aba"]
, the output should be
solution(inputArray) = ["aba", "vcd", "aba"]
.
Input/Output
-
[execution time limit] 3 seconds (java)
-
[memory limit] 1 GB
-
[input] array.string inputArray
A non-empty array.
Guaranteed constraints:
1 ≤ inputArray.length ≤ 10
,
1 ≤ inputArray[i].length ≤ 10
.
-
[output] array.string
Array of the longest strings, stored in the same order as in the inputArray
.
[Java] Syntax Tips
## Solutions:
-
JS solution
|
function solution(inputArray) { |
|
let maxLen = 0 |
|
let solution = [] |
|
for(const x of inputArray){ |
|
if(x.length > maxLen){ |
|
maxLen = x.length |
|
solution = [x] |
|
}else if (x.length === maxLen){ |
|
solution.push(x) |
|
} |
|
} |
|
return solution |
|
} |
-
Java solution
|
static String[] solution(String[] inputArray) { |
|
var maxLen = 0; |
|
var strings = new StringBuilder(); |
|
for(String input: inputArray){ |
|
var len = input.length(); |
|
if(len > maxLen){ |
|
maxLen = len; |
|
strings = new StringBuilder(input); |
|
}else if(len == maxLen){ |
|
strings.append(input); |
|
} |
|
} |
|
return strings.toString().split("(?<=\\G.{"+ maxLen + "})");// Match every maxLen characters |
|
} |