Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
class Solution {
public:
int firstUniqChar(string s) {
int index=-1;
int record1[100]={};
int record2[100000]={};
if(s.length()==0){
return -1;
}
for(int i=0;i<s.length();i++){
//就是利用一个桶排序做计数。
record1[s[i]-'a']++;
record2[i]=s[i]-'a';//记录顺序位置在桶中的坐标。
}
for(int i=0;i<100000;i++){
if(record1[record2[i]]==1){
index= i;
break;
}
}
return index;
}
};
本文介绍了一种方法来查找给定字符串中的第一个不重复字符并返回其索引位置。如果不存在这样的字符,则返回-1。通过使用两个记录数组进行计数和定位,实现了高效的查找。

被折叠的 条评论
为什么被折叠?



