1. 题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).(从0开始计数)
2. 题目解析
给定一个字符串,让你求这个字符串只出现一次的字符,我们一般的想法都是遍历一遍字符串,依次和后面的相比较,如果一样的话,就去掉。这里的时间复杂度为(On*n)我们可以通过java中的hashmap去做,遍历一遍字符串,判断这个字符在不在hashmap中,如果不在,则输入map.put(str.charAt(i), 1);如果在,则int x = map.get(str.charAt(i)); map.put(str.charAt(i), ++x);因为hashmap是无序的,所以我们最后需要再遍历一遍字符串,如果当前map.get(str.charAt(i)) == 1我们直接返回i,遍历完后,返回-1
3. 题目代码
import java
.util
.HashMap
;
public class Solution {
public int FirstNotRepeatingChar(String str
) {
HashMap
<Character, Integer> map
= new HashMap<>();
for (int i
= 0; i
< str
.length(); i
++) {
if (map
.containsKey(str
.charAt(i
))) {
int x
= map
.get(str
.charAt(i
));
map
.put(str
.charAt(i
), ++x
);
} else {
map
.put(str
.charAt(i
), 1);
}
}
for(int i
= 0; i
< str
.length(); i
++) {
if(map
.get(str
.charAt(i
)) == 1) {
return i
;
}
}
return -1;
}
}