Skip to content

Commit caf17a9

Browse files
committed
Add FirstUniqueCharacterInString task solution
1 parent d1ee5cb commit caf17a9

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package by.andd3dfx.string;
2+
3+
import java.util.LinkedHashMap;
4+
5+
/**
6+
* <pre>
7+
* <a href="https://leetcode.com/problems/first-unique-character-in-a-string/description/">Task description</a>
8+
*
9+
* Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
10+
*
11+
* Example 1:
12+
* Input: s = "leetcode"
13+
* Output: 0
14+
* Explanation: The character 'l' at index 0 is the first character that does not occur at any other index.
15+
*
16+
* Example 2:
17+
* Input: s = "loveleetcode"
18+
* Output: 2
19+
*
20+
* Example 3:
21+
* Input: s = "aabb"
22+
* Output: -1
23+
* </pre>
24+
*/
25+
public class FirstUniqueCharacterInString {
26+
27+
public static int firstUniqChar(String s) {
28+
LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();
29+
for (var ch : s.toCharArray()) {
30+
if (map.containsKey(ch)) {
31+
map.put(ch, map.get(ch) + 1);
32+
} else {
33+
map.put(ch, 1);
34+
}
35+
}
36+
for (var entry : map.entrySet()) {
37+
if (entry.getValue() == 1) {
38+
return s.indexOf(entry.getKey());
39+
}
40+
}
41+
return -1;
42+
}
43+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package by.andd3dfx.string;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
5+
import org.junit.Test;
6+
7+
public class FirstUniqueCharacterInStringTest {
8+
9+
@Test
10+
public void firstUniqChar() {
11+
assertThat(FirstUniqueCharacterInString.firstUniqChar("leetcode"))
12+
.isEqualTo(0);
13+
assertThat(FirstUniqueCharacterInString.firstUniqChar("loveleetcode"))
14+
.isEqualTo(2);
15+
assertThat(FirstUniqueCharacterInString.firstUniqChar("aabb"))
16+
.isEqualTo(-1);
17+
}
18+
}

0 commit comments

Comments
 (0)