Published
- 1 min read
First uniqie character in a string
First unique character in a string Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
//Input : loveleetcode
private int firstUniqueCharacterArrayApproach(String str) {
//loveleetcode, but the problem is unordered map
int arr [] = new int[26];
for (int i =0; i < str.length(); i++) {
int ch = str.charAt(i) - 'a';
arr[ch]++; //maintain character frequency
}
for (int i =0; i < str.length(); i++) {
if(arr[str.charAt(i) - 'a'] == 1) {
return i;
}
}
return -1;
}
private int firstUniqueCharacterMapApproach(String str) {
//loveleetcode, but the problem is unordered map, for this we need a iterate over a array again
Map<Character, Integer> frequencyMap = new HashMap<>();
for (int i =0; i < str.length(); i++) {
frequencyMap.put(str.charAt(i), frequencyMap.getOrDefault(str.charAt(i), 0)+1);
}
for (int i =0; i < str.length(); i++) {
if(frequencyMap.get(str.charAt(i)) == 1) {
return i;
}
}
return -1;
}