Hi guys,
I wrote some code for finding the three longest words in a string. The code I wrote seem too complicated, is there a better way to appoarch this?
public class Size {
public String[] threeLongest(String word){
String[] three = new String[3];
String[] words = word.split(" ");
three[0] = longest(word);
three[1] = find(words, three[0]);
three[2] = find(words, three[0], three[1]);
return three;
}
public String longest(String word){
String[] words = word.split(" ");
int largestLength = -1;
String largestWord ="";
for(String x:words)
if(x.length()>=largestLength){
largestWord = x;
largestLength = x.length();
}
return largestWord;
}
private String find(String[] words, String longest){
String l1 ="";
int lnum = -1;
for(String x: words){
if(!x.equals(longest)){
if(x.length()>= lnum){
l1=x;
lnum=x.length();
}
}
}
return l1;
}
private String find(String[] words, String l1, String l2){
String longest ="";
int lnum = -1;
for(String x: words){
if(!x.equals(l1)){
if(!x.equals(l2))
if(x.length()>= lnum){
longest=x;
lnum=x.length();
}
}
}
return longest;
}
}