标签:HERE active https 统计字符数 type ring i++ markdown title
原题网址:https://www.lintcode.com/problem/first-unique-character-in-a-string/description
给出一个字符串,找出第一个只出现一次的字符。
对于 "abaccdeff"
, ‘b‘
为第一个只出现一次的字符.
class Solution {
public:
/**
* @param str: str: the given string
* @return: char: the first unique character in a given string
*/
char firstUniqChar(string &str) {
// Write your code here
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;
}
};
在网上搜了搜果然看到了更简洁的代码,真想拍自己一脑门…… 参考:https://www.cnblogs.com/grandyang/p/5802109.html
只用一个哈希表统计字符数量,然后遍历字符串,若当前字符数量为1则返回该字符。
AC代码:
class Solution {
public:
/**
* @param str: str: the given string
* @return: char: the first unique character in a given string
*/
char firstUniqChar(string &str) {
// Write your code here
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
标签:HERE active https 统计字符数 type ring i++ markdown title
原文地址:https://www.cnblogs.com/Tang-tangt/p/9189183.html