You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
🔥 First Unique Character in a String 🔥 || 3 Approaches || Simple Fast and Easy || with Explanation
Solution - 1 HashMap
classSolution {
intfirstUniqChar(String s) {
// hashmap to store the unique valuesHashMap<String, int?> map =HashMap();
// looping through each and every element in the Stringfor (int i =0; i < s.length; i++) {
// assigning the int as index for every element
map[s[i]] = (map[s[i]] ??0) +1;
}
// looping againfor (int i =0; i < s.length; i++) {
// if the element matches with index value as saved aboveif (map[s[i]] ==1) {
// than we will return that elementreturn i;
}
}
// sentinel valuereturn-1;
}
}
Solution - 2 Frequency Array
classSolution {
intfirstUniqChar(String s) {
// index as ansint ans =0;
// into array list of each and every characterList<String> chars = s.split("");
// if that character is inside the array of characterfor (String char in chars) {
// comparing first to last indexif (s.indexOf(char) == s.lastIndexOf(char)) {
// assigning the index to our valuereturn ans = s.indexOf(char);
} else {
ans =-1;
}
}
return ans;
}
}
Solution - 3
classSolution {
intfirstUniqChar(String s) {
// frequency of array based on the length of alphabets inn ENGLISHList<int> freq =List.filled(26, 0);
// looping through the length of stringfor (int i =0; i < s.length; i++)
// getting the index of the each individual string character
freq[s.codeUnitAt(i) -'a'.codeUnitAt(0)]++;
for (int i =0; i < s.length; i++)
// if it matches with index we will returnif (freq[s.codeUnitAt(i) -'a'.codeUnitAt(0)] ==1) return i;
return-1;
}
}