First Unique Character In String LeetCode
class Solution {
public int firstUniqChar(String s) {
LinkedHashMap<Character,Integer> map=new LinkedHashMap<Character,Integer>();
for(int i=0;i<s.length();i++){
if(map.containsKey(s.charAt(i))){
map.put(s.charAt(i),map.get(s.charAt(i))+1);
}
else{
map.put(s.charAt(i),1);
}
}
char a='\0';
//map.forEach((k,v)->System.out.println(k+"->"+v));
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
char key = entry.getKey();
int tab = entry.getValue();
if(tab==1){
a=key;
break;
}
}
return s.indexOf(a);
}
}
Approach:
Here first we will store all the characters and their frequency in LinkedHashMap.
[Reason for using linked hashmap is that insertion order will be preserved. The incoming order of characters in the map will remain the same. However, if we use only hashmap it will generate random order.]
Now traversing map with entry set and as soon as we get the first character with one frequency we will break the loop and return its index from the given string.
Time:O(N)[LeetCode Time: 28ms faster than 38.83%]
Space:O(N)[LeetCode Memory: 39.8MB less than 53.64%]
Thanks for Reading.😇
"Share Further To Increase Knowledge Treasure.😊"
Comments
Post a Comment