Recently, I attended an interview. They asked me to write a program to print unique alphabets and common characters from two strings. I wrote the code below to print the common characters:
String s1 = "I am living in India";
String s2 = "India is a beautiful country";
char[] s1Array = s1.toCharArray();
char[] s2Array = s2.toCharArray();
LinkedHashSet<Character> s1CharSet = new LinkedHashSet<Character>();
LinkedHashSet<Character> s2CharSet = new LinkedHashSet<Character>();
for(char kc : s1Array){
s1CharSet.add(kc);
}
for(char c: s2Array){
s2CharSet.add(c);
}
s1CharSet.retainAll(s2CharSet);
if(s1CharSet.size()==0){
System.out.println("There are no common characters between the two strings");
}
else{
System.out.println(s1CharSet);
}
}
but they said they are not satisfied with my answer. I guess it's because they are not expecting retainAll
. So, please tell me the right way of programming to satisfy them in the future.
I even Googled but I didn't find any good, understandable links.
So, how to print unique and common characters from two strings without using retainAll
?
Any code would be appreciated.