题目来源:链接: [https://leetcode-cn.com/problems/first-unique-character-in-a-string/].
387. 字符串中的第一个唯一字符
1.问题描述
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例1:
输入:
s = "leetcode"
返回 0.
s = "loveleetcode",
返回 2.
注意事项:
您可以假定该字符串只包含小写字母。
2.我的解决方案
easy 类型题目
利用空间换取时间。
我的代码:
class Solution {
public:
int firstUniqChar(string s) {
int tmp[26] = {0};
int i = 0;
for(auto c : s)
{
++tmp[c-'a']; //将 s 中每个字母出现的 次数存起来。 a对应0 b对应1 。。z对应25
}
for(i = 0; i < s.size(); ++i)
{
if( tmp[s[i]-'a'] == 1) //从s的第一个字母 查 只有一次的索引号
{
return i;
}
}
return -1;
}
};
原来我也有这一天啊
执行用时 : 24 ms, 在First Unique Character in a String的C++提交中击败了99.78% 的用户
内存消耗 : 12.8 MB, 在First Unique Character in a String的C++提交中击败了0.93% 的用户
3.大神们的解决方案
大神的 12ms 算法。。。
class Solution {
public:
int firstUniqChar(std::string s) {
std::vector<int> flag(26, -1);
int size = s.length(), i = 0;
while(i < size) {
flag[s[i++] - 'a']= flag[s[i] - 'a'] == -1 ? i : -2;
}
sort(flag.begin(), flag.end());
i = 0;
while(i < 26) {
if(flag[i] > -1)
return flag[i];
i++;
}
return -1;
}
};
4.我的收获
空间换取时间 很好用呀
2019/4/9 胡云层 于南京 50