描述
在一个长为 字符串中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).(从0开始计数)
数据范围:0 \le n \le 100000≤n≤10000,且字符串只有字母组成。
要求:空间复杂度 O(n)O(n),时间复杂度 O(n)O(n)
方法一:数组
巧妙利用字母的ASCII码,因为我们知道小写字母z的ASCII码值为122。所以我们可以使用计数的方法,开辟一个空间为123(数组下标从0开始)的数组,使用ASCII码(对应数组的下标)表示字母,去统计字母出现的次数。
最后我们只需要遍历一遍字符串,找到那个只出现一次的字符即可
package test;
public class FirstNotRepeatChar2 {
public static void main(String[] args) {
FirstNotRepeatChar2 firstNotRepeatChar2 =
new FirstNotRepeatChar2();
int index = firstNotRepeatChar2.FirstNotRepeatingChar("google");
System.out.println(index);
}
//将arr数组整个作为一个大的计数器,开始计数器都是0,
//用字符转换成ascii来代表下标,定位这个字符,并统计个数
//开辟足够多的空间来计数
public int FirstNotRepeatingChar(String str) {
int arr [] =new int[150];
//统计个数
for (int i = 0; i < str.length(); i++) {
arr[str.charAt(i)]++;//定位下标,来代表字母
}
//循环str,判断个数等于1的位置
for (int i = 0; i < str.length(); i++) {
//元素统计的个数,即计数放在arr整形数组中
if(arr[str.charAt(i) ] ==1){
return i;
}
}
return -1;
}
}