Question : Remove Duplicate characters from a string.
Solution :
Basically the solution involves counting the occurences of characters in the string .
First solution uses an in-built Hashtable :
public static String removeDuplicateCharHash(String ip){
Hashtable<Character, Integer> ht = new Hashtable<Character, Integer>();
String op = new String("");
for(int i=0;i<ip.length();i++){
Character ch = ip.charAt(i);
if (! ht.containsKey(ch))
{ op = op + ch; ht.put(ch, new Integer(1)); }
}
return op;
}
Second Solution uses a bit vector which is used as a hastable:
public static String removeDuplicateChar(String ip){
// Initialize the bit vector
int ht[] = new int[256];
for (int i=0;i<256;i++)
ht[i] = 0;
String op = "";
for (int i=0;i<ip.length();i++){
char ch = ip.charAt(i);
if (ht[ch] == 0)
{op = op + ch; ht[ch]++;}
}
return op;
}
Solution :
Basically the solution involves counting the occurences of characters in the string .
First solution uses an in-built Hashtable :
public static String removeDuplicateCharHash(String ip){
Hashtable<Character, Integer> ht = new Hashtable<Character, Integer>();
String op = new String("");
for(int i=0;i<ip.length();i++){
Character ch = ip.charAt(i);
if (! ht.containsKey(ch))
{ op = op + ch; ht.put(ch, new Integer(1)); }
}
return op;
}
Second Solution uses a bit vector which is used as a hastable:
public static String removeDuplicateChar(String ip){
// Initialize the bit vector
int ht[] = new int[256];
for (int i=0;i<256;i++)
ht[i] = 0;
String op = "";
for (int i=0;i<ip.length();i++){
char ch = ip.charAt(i);
if (ht[ch] == 0)
{op = op + ch; ht[ch]++;}
}
return op;
}
No comments:
Post a Comment