Problem : Remove duplicates from string given " bananas " Return "bans"
Write code for both O(n) and O(n2) solutions
Solution using BitSet:
public class RemoveDuplicatesFromString {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
String str = input.nextLine();
str = str.toLowerCase();
BitSet bitset = new BitSet(26);
for(int i=0;i<str.length();i++)
{
if(!bitset.get(str.charAt(i)))
{
bitset.set(str.charAt(i));
System.out.print(str.charAt(i));
}
}
}
}
Solution using HashSet:
public class RemoveDuplicatesFromString {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
String str = input.nextLine();
str = str.toLowerCase();
HashSet<Character> bitset=new HashSet<Character>();
for(int i=0;i<str.length();i++)
{
if(!bitset.contains(str.charAt(i)))
{
bitset.add(str.charAt(i));
System.out.print(str.charAt(i));
}
}
}
}
References :
1) http://docs.oracle.com/javase/1.5.0/docs/api/java/util/class-use/BitSet.html
2) http://docs.oracle.com/javase/1.4.2/docs/api/java/util/BitSet.html
Write code for both O(n) and O(n2) solutions
Solution using BitSet:
public class RemoveDuplicatesFromString {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
String str = input.nextLine();
str = str.toLowerCase();
BitSet bitset = new BitSet(26);
for(int i=0;i<str.length();i++)
{
if(!bitset.get(str.charAt(i)))
{
bitset.set(str.charAt(i));
System.out.print(str.charAt(i));
}
}
}
}
Solution using HashSet:
public class RemoveDuplicatesFromString {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
String str = input.nextLine();
str = str.toLowerCase();
HashSet<Character> bitset=new HashSet<Character>();
for(int i=0;i<str.length();i++)
{
if(!bitset.contains(str.charAt(i)))
{
bitset.add(str.charAt(i));
System.out.print(str.charAt(i));
}
}
}
}
References :
1) http://docs.oracle.com/javase/1.5.0/docs/api/java/util/class-use/BitSet.html
2) http://docs.oracle.com/javase/1.4.2/docs/api/java/util/BitSet.html
No comments:
Post a Comment