题目:
在一个字符串(1<=字符串长度<=10000)中找到第一个只出现一次的字符,并返回它的位置。
解题思路:
1.共遍历两次字符串,第一次遍历统计每个字符出现的次数,第二次遍历遇到次数为1的字符返回它的位置即可。 2.char占一个字节,共8bit,共有256种可能(256个字符),我们开一个大小为256的数组来保存每个字符出现的次数。 3.时间复杂度
O(n)
,空间复杂度
O(1)
。
java实现:
public class Solution {
public int FirstNotRepeatingChar(String
str) {
int [] alph =
new int [
256];
for(
int i =
0; i <
str.length(); i ++){
char c =
str.charAt(i);
alph[c] +=
1;
}
for(
int i =
0; i <
str.length(); i ++){
if(alph[
str.charAt(i)] ==
1)
return i;
}
return -
1;
}
}