Skip to content

Commit ee2d328

Browse files
authored
Update First Unique Character in a String.java
1 parent e5aa2fd commit ee2d328

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

Java/First Unique Character in a String.java

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
E
2-
1516264417
2+
1533602948
33
tags: Hash Table, String
44

55
方法1: 按照题意, 找到第一个 first index == last index的字母.
@@ -19,6 +19,18 @@
1919
return 2.
2020
Note: You may assume the string contain only lowercase letters.
2121
*/
22+
class Solution {
23+
public int firstUniqChar(String s) {
24+
int[] freq = new int[256];
25+
for (char c : s.toCharArray()) {
26+
freq[c - 'a']++;
27+
}
28+
for (int i = 0; i < s.length(); i++) {
29+
if (freq[s.charAt(i) - 'a'] == 1) return i;
30+
}
31+
return -1;
32+
}
33+
}
2234

2335
/*
2436
Direclty compare first occurance of a character && last occurance, see if at same spot
@@ -71,4 +83,4 @@ public int firstUniqChar(String s) {
7183
}
7284
}
7385

74-
```
86+
```

0 commit comments

Comments
 (0)