【题目】
在字符串 s 中找出第一个只出现一次的字符,如果没有,返回一个单空格,s 只包含小写字母。您返回的结果必须是这几个值中的一个 {“Sunday”,
来源:leetcode
链接:https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof/
【示例】
s = “abaccdeff”
返回 “b”
【示例2】
s = “”
返回 " "
【代码】
class Solution {
public:
char firstUniqChar(string s) {
if(s=="")
return ' ';
s+=" ";
int len=s.size();
for(int i=0;i<len;i++)
if(s.find(s[i],i+1)==-1&&s.find(s[i])==i)
return s[i];
return ' ';
}
};
【方法二】
class Solution {
private:
map<char,int> m;
public:
char firstUniqChar(string s) {
for(auto x:s)
m[x]++;
for(auto x:s)
if(m[x]==1)
return x;
return ' ';
}
};
【方法三】
static int n=[](){
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
return 0;
}();
class Solution {
private:
const static int SIZE = 26;
// 第一次出现的位置
int firstIndex[SIZE];
public:
char firstUniqChar(string s) {
if (s == "") {
return ' ';
}
// 初始化
memset(firstIndex, -1, SIZE * sizeof(int));
for (int i = 0 ; i < s.size() ; i ++) {
// 如果没有出现过
if (firstIndex[s[i] - 'a'] < 0) {
firstIndex[s[i] - 'a'] = i;
} else {
// 出现过的话,将下标置为max
firstIndex[s[i] - 'a'] = INT_MAX;
}
}
int resutIndex = INT_MAX;
char resultChar;
for (int i = 0 ; i < SIZE ; i ++) {
if (firstIndex[i] < resutIndex && firstIndex[i] >= 0) {
resutIndex = firstIndex[i];
resultChar = 'a' + i;
}
}
if (resutIndex == INT_MAX) {
return ' ';
}
return resultChar;
}
};