-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirstCharacter.java
More file actions
37 lines (31 loc) · 829 Bytes
/
Copy pathFirstCharacter.java
File metadata and controls
37 lines (31 loc) · 829 Bytes
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
/*
input:givenastring
output:2
input:howareyou
output:2
*/
package hash;
import java.util.HashMap;
public class FirstCharacter {
public static int firstUniqChar(String str) {
if (str == null || str.length() == 0) {
return 0;
}
HashMap<Character, Integer> dic = new HashMap<Character, Integer>();
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (dic.containsKey(chars[i])) {
int newValue = dic.get(chars[i]) + 1;
dic.put(chars[i], newValue);
} else {
dic.put(chars[i], 1);
}
}
for (int i = 0; i < chars.length; i++) {
if (dic.get(chars[i]) == 1) {
return i;
}
}
return -1;
}
}