题目描述:
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.
Note: You may assume the string contain only lowercase letters.
思路:
因为小写字母的个数是有限的,一共26个,所以可以创建一个长度为26的整型数组。遍历给出的字符串,某个字母出现一次,整型数组对应位置的值加1。然后再遍历一次,按先后顺序检查每个字母对应位置的数值,第一个出现为1的即为所求。
代码
class Solution {
public int firstUniqChar(String s) {
int[] num = new int[26];
for(int i = 0;i<s.length();i++){
num[s.charAt(i)-'a']++;
}
for(int i =0;i<s.length();i++){
if(num[s.charAt(i)-'a']==1){
return i;
}
}
return -1;
}
}