An open API service indexing awesome lists of open source software.

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

Awesome Lists containing this project

README

        

# First unique character in a string
## https://leetcode.com/problems/first-unique-character-in-a-string

Given 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