zoukankan      html  css  js  c++  java
  • PAT A1071 Speech Patterns (25分)


    思路:
    统计单词个数,大小写字母+数字的组合是合法的单词,给出一个字符串,求出现的合法的单词的个数最多的那个单词,以及它出现的次数。如果有并列的,那么输出字典序里面的第一个(注意:由于map内部是由红黑树实现的,会自动按照从小往大的顺序自动排列键值,因子首先访问到的键值就是字典序最小的)
    利用map,根据key从小到大排序则直接map<string,int>
    总结:
    这道题没有太多需要注意的地方,可能需要稍微复习一下string的常用公式
    依然要注意:string虽然以结束但是访问时不会遍历到,所以在这道题我的解决方案里面需要在处理最后一个单词

    #include<iostream>
    #include<map>
    #include<string>
    using namespace std;
    map<string,int> word;
    
    
    bool ischaracter(char c){
        if(c>='0'&&c<='9') return true;
        else if(c>='a'&&c<='z') return true;
        else if(c>='A'&&c<='Z') return true;
        else return false;
    }
    int main(){
        string speech;
        string w;
        getline(cin,speech);
        int pos = -1;//未指向
        int len = 0;
        for(int i = 0;i < speech.length();i++){
            if(ischaracter(speech[i])==true){
                if(speech[i]>='A'&&speech[i]<='Z') speech[i] = speech[i] - 'A'+'a';
                if(pos == -1) pos = i;
                len++;
            }else{
                if(pos!=-1){//有值
                    w = speech.substr(pos,len);
                    if(word.find(w)!=word.end()){
                        word[w]++;
                    }else{
                        word.insert(make_pair(w,1));
                    }
                }
                //初始化
                pos = -1;
                len = 0;
            }
        }
        if(pos!=-1){
           w = speech.substr(pos,len);
           if(word.find(w)!=word.end()){
               word[w]++;
           }else{
             word.insert(make_pair(w,1));
           }        
        }
        string mostword;
        int ans = 0;
        for(map<string,int>::iterator it = word.begin();it!=word.end();it++){
            if(it->second > ans){
                ans = it->second;
                mostword = it->first;
            }
        }
        cout<<mostword<<" "<<ans<<endl;
        return 0;
    }
    
  • 相关阅读:
    centos7 Nginx1.14+php7+mysql5.7 以及 centos7 Apache2.4+PHP7+mysql 安装 Linux 配置 composer 以及Python2.7升级到3.7
    微信遇到的几个小问题
    前段mui框架初识
    关于百度编辑器设置默认行间距段间距
    call与apply 以及闭包
    随笔日记2018 4.10 关于多选框
    关于JVM中的两个Survivor区
    (转)Struts2的工作原理
    (转)struts2的执行流程、工作原理
    (转)最大乘积分析(切绳子)
  • 原文地址:https://www.cnblogs.com/shuibeng/p/13586935.html
Copyright © 2011-2022 走看看