Fork me on GitHub

LeetCode-387:字符串中第一个唯一字符

本题为LeetCode中第387道题,较为简单

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

案例:

1
2
3
4
5
s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

注意事项: 您可以假定该字符串只包含小写字母。

先来看看博主的笨办法,这里我们使用了LinkedHashMap(因为有序,我们最先进去的字母就是最前面的字母),换成HashMap就不行,因为我们最终需要输出只出现一次的最早的字母,记住是最早出现且只出现了一次的字母,所以我们需要用LinkedHashMap来保证有序

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
/**
* @author RickYinPeng
* @ClassName First_Unique_Character_in_a_String
* @Description LeetCode中第387道题
* @date 2018/10/27/17:36
*
* 题目名称:字符串中的第一个唯一字符
*/
public class First_Unique_Character_in_a_String {

public static void main(String[] args) {
String s = "loveleetcode";
int i = firstUniqChar(s);
System.out.println(i);
}

/**
* 博主的笨办法
* @param s
* @return
*/
public static int firstUniqChar(String s) {
HashMap<Character,Integer> map = new LinkedHashMap<>();
for(int i = 0;i<s.length();i++){
char index = s.charAt(i);
if(!map.containsKey(index)){
map.put(index,1);
}else{
map.put(index,map.get(index)+1);
}
}

for(Map.Entry<Character,Integer> entry: map.entrySet()){
if(entry.getValue()==1){
Character key = entry.getKey();
int indexOf = s.indexOf(key);
return indexOf;
}
}
return -1;
}
}

再来看看排行榜第一的大佬:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* 这可能就是大佬吧,记下就行了
* @param s
* @return
*/
public static int firstUniqChar_2(String s){
int res = -1;

for(char ch='a'; ch<='z'; ch++) {
int index = s.indexOf(ch);
if(index != -1 && index == s.lastIndexOf(ch)) {
res = res == -1?index:Math.min(res, index);
}
}
return res;
}