Appearance
0387-字符串中的第一个唯一字符
https://leetcode.cn/problems/first-unique-character-in-a-string
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例:
s = "leetcode"
返回 0
s = "loveleetcode"
返回 2
提示:你可以假定该字符串只包含小写字母。
思路:暴力法循环两次
暴力循环两次O(n^2)尝试hash表缓存
csharp
public class Solution {
public int FirstUniqChar(string s) {
if(s.Length <= 1){
return s.Length -1;
}
//循环两次
for(int i=0; i<s.Length; i++){
bool found = false;
for(int j=0; j<s.Length; j++){
if(s[i] == s[j] && i != j){
found = true;
break;
}
}
if(!found){
return i;
}
}
return -1;
}
}
思路2:hash表缓存
csharp
public class Solution{
public int FirstUniqChar(string s){
Dictionary<char,int> dict = new Dictionary<char,int>();
for(int i=0; i<s.Length; i++){
if(dict.ContainsKey(s[i])){
dict[s[i]]++;
}
else{
dict.Add(s[i],1);
}
}
//遍历拿出第一个为1的索引
//注意是循环原数组,不是字典
for(int i=0; i<s.Length; i++){
if(dict[s[i]] == 1){
return i;
}
}
return -1;
}
}
AlgoPress