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.
String[] solution(String[] inputArray) {
// 문자열을 담아둘 자료구조
// 추가 혹은 비우기만 할 것이므로 추가 및 삭제에 용이한 LinkedList 사용
LinkedList <String> list = new LinkedList<>();
// 이전 문자열 최대 길이
int length = 0;
for (int i = 0; i < inputArray.length; i ++) {
// 이전 문자열 최대 길이보다 현재 문자열 길이가 길 경우
if (inputArray[i].length() > length) {
// list 비우기
list.clear();
// 최대 길이 갱신
length = inputArray[i].length();
// list 에 추가
list.add(inputArray[i]);
// 이전 문자열 최대 길이와 같을 경우
} else if (inputArray[i].length() == length) {
// list 에 추가
list.add(inputArray[i]);
}
}
// list to Arrays
String [] result = new String [list.size()];
for (int i = 0; i < result.length; i ++) {
result[i] = list.get(i);
}
return result;
}