问题描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
class Solution {
public:
int FirstNotRepeatingChar(string str) {
if(str.empty()) return -1;
unordered_map<char,int> freq;
for(int i=0;i<str.size();i++){
char temp=str[i];
freq[temp]++;
}
int ans=str.size();
for(auto a:freq){
if(a.second==1){
int ret=str.find(a.first);
ans=min(ans,ret);
}
}
return ans==str.size()?-1:ans;
}
};
问题描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
class Solution
{
public:
string s="";
int hash[256]={0};
//Insert one char from stringstream
void Insert(char ch)
{
s=s+ch;
hash[ch]++;
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce()
{
int len=s.size();
for(int i=0;i<len;++i){
if(hash[s[i]]==1) return s[i];
}
return '#';
}
};