目录
(2)sizeof()、strlen()、length()、size()
题:实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。如果当前字符流没有存在出现一次的字符,返回#字符。(c++)
解法一.hashmap
#include<iostream>
using namespace std;
#include<map>
class Solution
{
public:
//Insert one char from stringstream
void Insert(char ch)
{
str += ch;//将字符流保存在string中
charMap[ch]++;//统计字符流中每个字符出现的次数
cout<<"str:"<<str<<" key:"<<ch<<" value:"<<charMap[ch]<<" map:"<<endl;
map<char,int>::iterator iter;
for(iter = charMap.begin(); iter != charMap.end(); iter++)
cout<<iter->first<<' '<<iter->second<<endl;
}
//return the first appearence-once-char in current stringstream
char FirstAppearingOnce()
{ //遍历str,从哈希表中找到第一个出现一次的字符
for(int i = 0; i< str.size(); i++){
if(charMap[str[i]] == 1){
return str[i];
}
}
return '#';
}
private:
string str = "";
map<char,int> charMap;
};
int main(){
Solution so;
char c[]="google";
for(int j=0;j<sizeof(c)-1;j++){
so.Insert(c[j]);//一个个输入字符流
}
cout<<so.FirstAppearingOnce()<<endl;
return 0;
}
输出:
string类的源码,重载的+运算符可以对string和char类型进行相加:
string& operator+= ( const string& str );
1.map<key, value>的定义及插入
map是STL的一个关联容器,它提供一对一的hash。第一个可以称为关键字(key),每个关键字只能在map中出现一次,第二个可能称为该关键字的值(value),定义如map<key, value> M。
value_type、key_type、mapped_type类型:
map<string, int>::key_type s; //此时key的实例s的类型key_type 是string
map<string, int>::mapped_type num; //此时value的实例num类型mapped_type 是int
map<string, int>::value_type m; //此时map的实例m的类型value_type是pair<const string, int>,注意pair键值对中第一个元素的类型有const(不可修改).
key_type就表示map中key的类型。以下两句是一个意思:
map<string, int>::key_type s;
string s;
使用语法: