题目描述:
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.
求第一个不重复的字符。
比较直接的做法是用哈希,由于题目提示了s中完全是小写字母,可以使用int[26]的数组来代替哈希。
实现代码:
public class Solution {
public int FirstUniqChar(string s) {
var arr = new int[26];
var len = s.Length;
for (var i = 0;i < len; i++){
arr[s[i]-97]++;
}
for (var i = 0;i < len; i++){
if(arr[s[i]-97] == 1){
return i;
}
}
return -1;
}
}