题目
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例:
s = “leetcode”
返回 0
s = “loveleetcode”
返回 2
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
- 分析
建立一个数组int count[] 统计每一个字符出现的次数。
按照字符串s 的顺序遍历count[],如果出现是1,则返回当前的字符所对应的位置即可。
public int firstUniqChar(String s) {
int[] count=new int[256];
for(int i=0;i<s.length();i++){
char ch=s.charAt(i);
count[ch]++;
}
for(int i=0;i<s.length();i++){
char ch=s.charAt(i);
if(count[ch]==1){
return i;
}
}
return -1;
}