zoukankan      html  css  js  c++  java
  • 单词数 HDU 2072 字符串输入控制

    单词数 HDU 2072 字符串输入控制

    题意

    lily的好朋友xiaoou333最近很空,他想了一件没有什么意义的事情,就是统计一篇文章里不同单词的总数。下面你的任务是帮助xiaoou333解决这个问题。

    有多组数据,每组一行,每组就是一篇小文章。每篇小文章都是由小写字母和空格组成,没有标点符号,遇到#时表示输入结束。

    每组只输出一个整数,其单独成行,该整数代表一篇文章里不同单词的总数。

    解题思路

    我的是使用map来进行统计的,确实比较慢了一些,因为输入的问题代码也写的比较垃圾。之后看了网上的题解,代码写得让人拍案叫绝。下面两个代码就是从这个博客上看到的

    //方法一:使用gets全部读入,然后使用strtok函数进行分割,最后使用set容器来进行去重。
    //代码进行了一下修改。
    #include<cstdio>
    #include<cstring>
    #include<string>
    #include<iostream>
    #include<algorithm>
    #include<set>
    using namespace std;
    char buf[1024], delim[]=" ", *p;
    set<string> w;
    int main()
    {
    	while(gets(buf)!=NULL) //gets函数在正常情况下会返回与参数相同的指针,在错误的情况下返回NULL 
    	{
    		if(strcmp(buf, "#")==0)
    			break;
    		w.clear();
    		p=strtok(buf, delim);
    		while(p)
    		{
    			w.insert(p);
    			p=strtok(NULL, delim);
    		}
    		printf("%d
    ", w.size());
    	}
    	return 0;
    }
    
    /* HDU2072 单词数 */
    #include <iostream>
    #include <cstdio>
    #include <sstream> //这个包含istringstream,ostringstream,stringstream三个函数
    #include <set>
    using namespace std;
    int main()
    {
        string s;
     
        while(getline(cin, s) && s != "#") {
            stringstream sin(s);
            set<string> words;
            string w;
            while(sin >> w)
                words.insert(w);
            cout << words.size() << endl;
        }
        return 0;
    }
    

    另外附上自己的比赛时写的小代码。

    #include<cstdio>
    #include<cstring>
    #include<iostream>
    #include<cstring>
    #include<algorithm>
    #include<map>
    using namespace std;
    const int maxn=1e5+7;
    map<string, int> mp;
    char str[maxn];
    char a[maxn];
    int main()
    {
    	int ans=0, i, len;
    	char tmp;
    	while(gets(str)&& str[0]!='#')	
    	{
    		ans=0;
    		mp.clear();
    		len=0;
    		while( sscanf(str+len, "%s", a)!=EOF)
    		{
    			if(mp[a]==0)
    			{
    				mp[a]=1;
    				ans++;
    			}
    			len+=strlen(a)-1;
    			for(int i=1; ; i++)
    			{
    				if(*(str+len+i)!=' ')
    				{
    					len=len+i;
    					break;
    				}
    			}
    		}
    		printf("%d
    ", ans);
    	}
    	return 0;
     } 
    
    欢迎评论交流!
  • 相关阅读:
    struts2知识系统整理
    JavaScript onload
    百度云如何为用户分配内存空间
    集合运算
    [hdu3530]单调队列
    [hdu4911]逆序对相关
    [hdu5199]统计数据的水题
    [hdu5200]离线+标记
    [hdu5204]水题
    [hdu5203]计数水题
  • 原文地址:https://www.cnblogs.com/alking1001/p/11765914.html
Copyright © 2011-2022 走看看