-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathFirstUniqueCharacterInAString.java
More file actions
63 lines (57 loc) · 1.67 KB
/
Copy pathFirstUniqueCharacterInAString.java
File metadata and controls
63 lines (57 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* <p>给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。</p>
*
* <p> </p>
*
* <p><strong>示例:</strong></p>
*
* <pre>s = "leetcode"
* 返回 0
*
* s = "loveleetcode"
* 返回 2
* </pre>
*
* <p> </p>
*
* <p><strong>提示:</strong>你可以假定该字符串只包含小写字母。</p>
* <div><div>Related Topics</div><div><li>队列</li><li>哈希表</li><li>字符串</li><li>计数</li></div></div><br><div><li>👍 497</li><li>👎 0</li></div>
*/
package leetcode9;
public class FirstUniqueCharacterInAString {
public static void main(String[] args) {
Solution solution = new FirstUniqueCharacterInAString().new Solution();
}
class Solution {
public int firstUniqChar(String s) {
int[] arr = new int[26];
for (int i = 0; i < s.length(); i++) {
arr[s.charAt(i) - 0x61]++;
}
for (int i = 0; i < s.length(); i++) {
if (arr[s.charAt(i) - 0x61] == 1) {
return i;
}
}
return -1;
}
}
class Solution2 {
public int firstUniqChar(String s) {
if (s == null || s.length() == 0) {
return -1;
}
int[] memo = new int[26];
char[] arr = s.toCharArray();
for (char c : arr) {
memo[c - 'a']++;
}
for (int i = 0; i < arr.length; i++) {
if (memo[arr[i] - 'a'] < 2) {
return i;
}
}
return -1;
}
}
}