算法提高 不同单词个数统计
时间限制:1.0s 内存限制:512.0MB
提交此题问题描述
编写一个程序,输入一个句子,然后统计出这个句子当中不同的单词个数。例如:对于句子“one little two little three little boys”,总共有5个不同的单词:one, little, two, three, boys。
说明:(1)由于句子当中包含有空格,所以应该用gets函数来输入这个句子;(2)输入的句子当中只包含英文字符和空格,单词之间用一个空格隔开;(3)不用考虑单词的大小写,假设输入的都是小写字符;(4)句子长度不超过100个字符。
输入格式:输入只有一行,即一个英文句子。
输出格式:输出只有一行,是一个整数,表示句子中不同单词的个数。
输入输出样例
样例输入
one little two little three little boys
样例输出
5
这道题使用set集合最简单,因为set集合不能存入相同的值,用来存不同单词的数量最好不过,当然,也可以不用set,使用字符串的hash函数,将一字符串转为int型的hash也可以实现判重。。
这里使用set,现在的问题就在于怎么获取一字符串里面的单词,并保存在set中。
这里使用了cin的特性,自动过滤掉空格。。。不过测试输入的时候只能使用文件输入,控制台输入无法结束输入,因为会过滤掉回车(⊙o⊙),但OJ还是能通过的。
#include <iostream>
#include <string>
#include <algorithm>
#include<cstring>
#include<cmath>
#include<set>
using namespace std;
int main(){
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
set<string> s;
string a;
while(cin>>a)
s.insert(a);
cout<<s.size()<<endl;
return 0;
}
下面是好用的提取单词的函数
S为输入的字符串,splitchar为分隔符(单词就为‘ ’),vec保存结果
int Split(const string &s, const string &splitchar, vector <string> &vec)
{
string stmp = "";
string::size_type pos = 0, prev_pos = 0;
int j = 0;
vec.clear();
while ((pos=s.find_first_of(splitchar, pos)) != string::npos)
{
stmp = s.substr(prev_pos, pos - prev_pos);
vec.push_back(stmp);
prev_pos = ++pos;
}
stmp = s.substr(prev_pos, pos - prev_pos);
if (stmp.length() > 0)
{
vec.push_back(stmp);
}
return 0;
}
还有字符串hash函数
//BKDRHash算法,比较好用好记实用的一种hash算法:
unsigned int BKDRHash(char *str)
{
unsigned int seed = 131; // 31 131 1313 13131 131313 etc..
unsigned int hash = 0;
while (*str)
{
hash = hash * seed + (*str++);
}
return (hash & 0x7FFFFFFF);
}
//另一种:
unsigned int hash(char *url,int mod){
unsigned int n = 0;
char *b = (Char *) &n;
for(int i=0;url[i];++i)
b[i%4]^=url[i];
return n % mod;
}