Given a String Array how would you find the first unique String element in the array
public static String UniqueString(String[] s) {
String str ="";
for(int i=0;i<s.length;i++) {
for(int j=i+1;j<s.length;j++) {
System.out.println(s[i]+" "+s[j]);
str = s[i];
if(str==s[j]) {
break;
}
}if(!(str==s[i+1])){
return str;
}
}
return str;
}
so a String array of {Dog,Cat,Dog,Wolf,lion} would return as Cat
You were very close to a working solution, you need a flag to indicate whether you found the String
again in s
(not sure where you got names
). Also we compare String
(s) with .equals
(not ==
). And method names start with a lower case letter. Something like,
public static String uniqueString(String[] s) {
for (int i = 0; i < s.length; i++) {
boolean unique = true;
for (int j = i + 1; j < s.length; j++) {
if (s[j].equals(s[i])) {
s[j] = s[s.length - 1]; // <-- handle bug, ensure that dupes aren't
// found again.
unique = false;
break;
}
}
if (unique) {
return s[i];
}
}
return "";
}