public class Solution {
public int FirstNotRepeatingChar(String str) {
char[] chars = str.toCharArray();
int count = 0;int temp=-1;
for (int i = 0; i < chars.length; i++) {
for (int j = 0; j < chars.length;j++){
if (i==j){
continue;
}
if (chars[i]!=chars[j]){
count++;
}
if (chars[i] == chars[j]) {
count = 0;
break;
}
}
if(count!=0){
temp=i;
break;
}
}
return temp;
}
}
官方题解:
这是一篇针对初学者的题解。共用两种方法解决。
知识点:哈希,bitset
难度:一星
方法一:哈希表
1、将字符当成哈希表中的key,第一次出现时候为true,重复出现则置为false;
2、遍历数组,拿到第一个在哈希表中的value为true的字符。
public int FirstNotRepeatingChar(String str) {
HashMap<Character,Boolean> map = new HashMap<>();
char[] chars = str.toCharArray();
// 初始化哈希表,重复出现的置为false,否则为true
for(char c:chars){
if(map.containsKey(c)){
map.put(c,false);
}else{
map.put(c,true);
}
}
// 二次遍历字符数组,若其在哈希表中的value为true,则返回下标
for(int i = 0; i < chars.length; i++){
if(map.get(chars[i])){
return i;
}
}
// 没有符合条件的则返回-1
return -1;
}
复杂度分析:
时间复杂度: O(N)。N为字符串的长度,因为需要遍历两轮字符串,所以为2N,使用大O表示法则为O(N)。
空间复杂度:O(1)。使用到的辅助空间为哈希表的空间,由于题目给出所出现的字符为大小写字母,所以也就是说只需要占用O(32)的空间,则空间复杂度为O(1),常数级别。
方法二:数组
巧妙利用字母的ASCII码,因为我们知道小写字母z的ASCII码值为122。所以我们可以使用计数的方法,开辟一个空间为123(数组下标从0开始)的数组,使用ASCII码(对应数组的下标)表示字母,去统计字母出现的次数。
最后我们只需要遍历一遍字符串,找到那个只出现一次的字符即可。由于很简单,我们直接看代码:
public int FirstNotRepeatingChar(String str) {
// 开辟一个数组
int[] dp = new int[123];
// 存储字母出现的次数 例如: dp[122] = 2,表示:小写字母z,出现了两次
// 统计出现的次数
for (int i = 0; i < str.length(); i++) {
dp[str.charAt(i)]++;
}
// 遍历字符串,若字符只出现一次,则返回下标
for (int i = 0; i < str.length(); i++) {
if (dp[str.charAt(i)] == 1)
return i;
}
return -1;
}