码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 2072 单词数 --- 字符串处理

时间:2015-12-13 20:13:59      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
/* HDU 2072 单词数 --- 字符串处理 */
#include <cstdio> //C语言改成stdio.h即可
#include <cstring> //C语言改成string.h即可

const int maxn = 85;

int main()
{
    char *head1, *head2;
    char a[maxn];
    char b[maxn][maxn];
    int i, k, len, cnt1, cnt2;

    while (gets(a)){
        //遇到字符串"#‘则结束
        if (# == a[0]){
            break;
        }

        //处理末尾的连续空格
        len = strlen(a);
        for (i = len - 1; i >= 0; --i){
            if (  == a[i]){
                a[i] = 0; //末尾有空格则用空字符替换
            }
            else
                break;
        }//for(i)

        //处理开头的连续空格
        len = strlen(a);
        if (len == 0){ //全是空格的情况特殊处理
            printf("0\n");
            continue;
        }
        for (i = 0; i < len; ++i){
            if (  == a[i]){
                a[i] = 0;
            }
            else{
                //遇到非空格
                head1 = a + i; //记录新的开头
                break;
            }
        }//for(i)
        
        len = strlen(head1);
        //在字符串末尾补上一个空格以便处理最后一个单词
        head1[len] =  ;
        head1[len + 1] = 0; 
        
        head2 = head1;
        cnt1 = 0; //cnt1统计单词数(可能重复)
        for (i = 0; i <= len; ++i){
            if (  == head1[i]){
                head1[i] = 0;
                //当前点是空格而后一个点不是空格 则后一个点即为新的单词起点
                if (  != head1[i + 1]){
                    //记录上一个单词并更新单词数
                    strcpy(b[cnt1], head2);
                    ++cnt1;
                    head2 = head1 + i + 1; //更新新的单词起点
                }
            }
        }//for(i)

        //处理相同的单词数
        cnt2 = cnt1;
        for (i = 0; i < cnt1; ++i){
            if (b[i][0] != #){
                for (k = i + 1; k < cnt1; ++k){
                    if (b[k][0] != # && strcmp(b[i], b[k]) == 0){
                        --cnt2;
                        b[k][0] = #; //已经判断是否重复则不再判断
                    }
                }//for(k)
                b[i][0] = #; //到此 和b[i]相同的单词第一个字符已经全部设置成‘#‘
            }//if
        }//for(i)
        printf("%d\n", cnt2);
    }//while(gets)

    return 0;
}
View Code

 

HDU 2072 单词数 --- 字符串处理

标签:

原文地址:http://www.cnblogs.com/tommychok/p/5043333.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!