给定一个字符串数组,返回包含其所有最长字符串的另一个数组。
For (String [] x = {"serm", "aa", "sazi", "vcd", "aba","kart"};)
输出
{"serm", "sazi" , "kart"}.
以下代码错误,我该怎么做才能修复它。
public class Tester {
public static void main(String[] args) {
Tester all = new Tester();
String [] x = {"serm", "aa", "sazi", "vcd", "aba","kart"};
String [] y = all.allLongestStrings(x);
System.out.println(y);
}
String[] allLongestStrings(String[] input) {
ArrayList<String> answer = new ArrayList<String>(
Arrays.asList(input[0]));
for (int i = 1; i < input.length; i++) {
if (input[i].length() == answer.get(0).length()) {
answer.add(input[i]);
}
if (input[i].length() > answer.get(0).length()) {
answer.add(input[i]);
}
}
return answer.toArray(new String[0]);
}
}
答案 0 :(得分:1)
我会给你解决方案,但作为功课,它将只是sudo代码 您的解决方案的问题是,您没有找到最长的字符串,但字符串大小相同或大于第一个元素的大小
let helper = []
let maxLength = 0;
for each string in array
if (len(string) >maxLength){
maxLength = len(string);
clear(helper)
}
if (len(string) == maxLength)
helper.add(string)
}
return helper;