题目
代码部分一(10ms 95.56%)
class Solution {
public int firstUniqChar(String s) {
char[] ch = s.toCharArray();
int[] map = new int[256];
int res = -1;
int n = ch.length;
for(int i = 0; i < n; i++){
map[ch[i]]++;
}
for(int i = 0; i < n; i++){
if(map[ch[i]] == 1){
res = i;
break;
}
}
return res;
}
}
1.将字符串转换为字符数组
2.创建一个整形数组来存放各个字母出现的次数(预设结果为-1)
3.按字符在字符串的顺序,来计算各个字符的次数
4.按字符在字符串的顺序,找到第一个字符出现个数为1的字符
5.返回结果坐标
代码部分二(10ms 95.30%)
class Solution {
public int firstUniqChar(String s) {
int res = -1;
for(char ch = 'a'; ch <= 'z'; ch++){
int i = s.indexOf(ch);
if(i != -1 && i == s.lastIndexOf(ch)){
res = res == -1 ? i : Math.min(res, i);
}
}
return res;
}
}
1.预设结果为-1
2.for循环遍历所有小写英字母
3.每次判断获取当前小写英文字母第一次出现的位置,字符串存在该字母且,第一次出现于最后一次出现的位置一样(只出现一次)时
4.若字母为第一次出现,比较结果集存放的字母位置与当前字母的位置哪个靠前
5.返回结果集