版权声明:哼!坏人!这是我辛辛苦苦码的! https://blog.csdn.net/DurianPudding/article/details/83098538
Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.
Examples:
s = “leetcode”
return 0.
s = “loveleetcode”,
return 2.
题意:
找到第一个唯一的字母的索引
思路:
先遍历一遍字符串,用一个数组统计各字母出现的次数,注意数组的索引对应字母的索引值次序(便于以后根据数组的索引就确定是哪个字母)。
再遍历一遍字符串,找到第一个次数为1的字母。注意遍历的是字符串,这样i就是字符串的索引,也就是结果。其实就是把字符串从头到位遍历,判断每个位置上的字母的次数是否为1,如果为1立刻终止,输出索引。
class Solution {
public int firstUniqChar(String s) {
int len = s.length();
int[] num = new int[26];
int ans = -1;
for(int i=0;i<len;i++){
num[s.charAt(i)-'a']++;
}
for(int i=0;i<len;i++){
if(num[s.charAt(i)-'a']==1){
//另一种return 方式是直接用i,省略了ans
//return i;
ans = i;
break;
}
}
//return -1;
return ans;
}
}