-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExtract_unique_char_Hashmap.txt
66 lines (48 loc) · 1.91 KB
/
Extract_unique_char_Hashmap.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
Extract Unique characters
Send Feedback
Given a string S, you need to remove all the duplicates. That means, the output string should contain each character only once. The respective order of characters should remain same, as in the input string.
Input format:
The first and only line of input contains a string, that denotes the value of S.
Output format :
The first and only line of output contains the updated string, as described in the task.
Constraints :
0 <= Length of S <= 10^8
Time Limit: 1 sec
Sample Input 1 :
ababacd
Sample Output 1 :
abcd
Sample Input 2 :
abcde
Sample Output 2 :
abcde
//Coded this on my own and saw the git repo to check my logic before implementing
import java.util.*;
public class Solution {
public static String uniqueChar(String str){
/* Your class should be named Solution
* Don't write main().
* Don't read input, it is passed as function argument.
* Return output and don't print it.
* Taking input and printing output is handled automatically.
*/
if(str.length() == 0 || str.length() == 1)
return str;
HashMap<Character, Boolean> map = new HashMap<>();
ArrayList<Character> arr = new ArrayList<>();
for(int i=0; i<str.length(); i++){
char c = str.charAt(i);
if(map.containsKey(c)){
continue;
}else{
map.put(c, true);
arr.add(c); //We use a ArrayList to store the charactres as to preserve the order in which they
} //occur in string. We cannot directly use Hashmap as the order of characters will change
} //and we cannot preserve the actual order of characters occuring in the string.
String s = "";
for(char key: arr){
s += key;
}
return s;
}
}