https://github.com/emahtab/first-unique-character-in-a-string
Find the first unique character in a string
https://github.com/emahtab/first-unique-character-in-a-string
hashmap leetcode problem-solving
Last synced: 3 months ago
JSON representation
Find the first unique character in a string
- Host: GitHub
- URL: https://github.com/emahtab/first-unique-character-in-a-string
- Owner: eMahtab
- Created: 2020-03-08T14:35:06.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2020-03-08T14:37:14.000Z (over 5 years ago)
- Last Synced: 2025-02-02T03:25:35.478Z (5 months ago)
- Topics: hashmap, leetcode, problem-solving
- Homepage:
- Size: 1000 Bytes
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# First unique character in a string
## https://leetcode.com/problems/first-unique-character-in-a-stringGiven a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
```
Examples:s = "leetcode"
return 0.s = "loveleetcode",
return 2.
```
**Note: You may assume the string contain only lowercase letters.**# Implementation :
```java
class Solution {
public int firstUniqChar(String s) {
HashMap count = new HashMap();
int n = s.length();
// build hash map : character and how often it appears
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
count.put(c, count.getOrDefault(c, 0) + 1);
}
// find the index
for (int i = 0; i < n; i++) {
if (count.get(s.charAt(i)) == 1)
return i;
}
return -1;
}
}
```# References :
https://leetcode.com/articles/first-unique-character-in-a-string