the array is
String[] words = {"Apple", "cheese", "Mississippi", "beer", "hand", "sandwich", "kadabra"};
my solutions were like this
1-
public static String LongestWord() {
String[] words = {"Apple", "cheese", "Mississippi", "beer", "hand",
"sandwich", "kadabra"};
String maxLength = words[0];
String newString = "";
for (String str : words) {
for (int i = 0; i < str.length(); i++) {
{
for (int j=i+1; j<str.length(); j++){
if="" (str.charat(i)="=" str.charat(j)){
newstring+="str.charAt(i);
}
}
(newstring.length()=""> maxLength.length()) {
maxLength = newString;
}
}
return maxLength;
}
the problem with the above solution is, it doesn't go through all characters of string it starts with "i" and there may be a duplicate before "i" and it won't detect it so it doesn't work.
2-
public static String LongestWord() {
String[] words = {"Apple", "cheese", "Mississippi", "beer", "hand", "sandwich", "kadabra"};
String maxLength = words[0];
String newString = "";
for (String str : words) {
for (int i = 0; i < str.length(); i++) {
{
for (int j=str.length()-1; j>=0; j--){
if (str.charAt(i) == str.charAt(j)){ newString+=str.charAt(i);
}
}
}
}
if (newString.length() > maxLength.length()) {
maxLength = newString;
}
}
return maxLength;
}
this one is closer to work but it still has a problem and that is when for example "i=0" and "j" reaches 0 then it will be equal because it's the same letter but not a duplicate, and i tried many others too, but nothing worked.
What I have tried:
I tried many solutions, but none of them compared all the characters to each other.