# 209 First Unique Character in a String

### 样例

AC代码：
```class Solution {
public:
/**
* @param str: str: the given string
* @return: char: the first unique character in a given string
*/
char firstUniqChar(string &str) {
char result;
int index=-1;
int n=str.size();
map<char,int> chCount;
map<char,int> chIndex;

for (int i=0;i<n;i++)
{
if (chCount.find(str[i])!=chCount.end())//统计字符数量;
{
chCount[str[i]]++;
}
else
{
chCount[str[i]]=1;
}
if (chIndex.find(str[i])==chIndex.end())//找到字符的第一个索引;
{
chIndex[str[i]]=i;
}
}

map<char,int>::iterator it;
for (it=chCount.begin();it!=chCount.end();it++)
{
if (it->second==1&&index==-1)
{
result=it->first;
index=chIndex[it->first];
}
else if (it->second==1&&chIndex[it->first]<index)
{
result=it->first;
index=chIndex[it->first];
}
}

return result;
}
};```

AC代码：

```class Solution {
public:
/**
* @param str: str: the given string
* @return: char: the first unique character in a given string
*/
char firstUniqChar(string &str) {
int n=str.size();
map<char,int> chCount;
for (int i=0;i<n;i++)
{
if (chCount.find(str[i])!=chCount.end())//统计字符数量;
{
chCount[str[i]]++;
}
else
{
chCount[str[i]]=1;
}
}
for (int i=0;i<n;i++)
{
if (chCount[str[i]]==1)
{
return str[i];
}
}
}
};```

209 First Unique Character in a String

(0)
(0)

0条