Oracle Interview Question
Software Engineer / Developerswell. you can compare every character of the string to every other character of the string. This will give you O ( n square )
another option is, you can soft the array on O ( n long n ) and then, iterate to look for duplicates.
What about that?
Does this work with definition??
public static void main(String[] args) {
String a="Shirish"; int y=0;
for(int i=0;i<a.length() && y!=0;i++)
{
for(int j=i+1;j<a.length();j++)
{
if(a.charAt(i)!=a.charAt(j))
y=1;
else {y=0;}
}
}
if(y==1)
System.out.print("no unique");
else
System.out.print(" unique");
}
}
/* this one is the easy approach to do this, simply scan the string from both side if found any match character then its not unique. time complexity O(n/2) i.e. O(n). */
public class uniquestring {
public static boolean test_string(String str){
int n = str.length()-1;
int i=0;
while(i<n)
{
if(str.charAt(i++)== str.charAt(n--))
return true;
}
return false;
}
public static void main(String[] args){
String st;
st = "ganesh";
System.out.println(test_string(st));
}
}
ganesh read the problem well before posting. Unique characters meas each one never is repeated in the string. No the other way around.
This wont work, because it would only find 'matched' characters if they happen to be at str[i] and str[n] - if the 2 identical characters are at str[i] and str[n-1], it would not find it? Did you try st = "ganegh";?
- .·´¯`·.´¯`·.¸¸.·´¯`·.¸><(((º> January 25, 2014