• 算法入门经典-第五章 例题5-4 反片语


    例题5-4 反片语 

    输入一些单词(以“#”为结束标志),找出所有满足如下条件的单词:该单词不能通过字母的重排,得到输入文本中的另一个单词。在判断是否满足条件是不分大小写,但是在输出时应保留输入时的大小写,按字典序进行排列(所有大写字母在所有小写字母前面)。 

    Sample input

    ladder came tape soon leader acme RIDE lone Dreis peat
     ScAlE orb  eye  Rides dealer  NotE derail LaCeS  drIed
    noel dire Disk mace Rob dries
    #

    Sample output

    Disk
    NotE
    derail
    drIed
    eye
    ladder
    soon

    分析


    这道题的解法很多,最简化的方式就是使用map容器。想到使用“标准化”。
    整体思路:
    1.写一个标准化函数(实现大写字母转换为小写(tolower()函数),单词排序。注意使用const是为了不改变s的初值)
    2.两个vector容器(words,ans),一个map容器(cnt)
    words存储所有的单词
    map存储标准化后对应单词以及出现次数的值,相当于一个表格。
    words经过查表map,把对应的符合值给ans
    3.输出

    代码:
    #include<iostream>
    #include<string>
    #include<vector>
    #include<algorithm>
    #include<cctype>
    #include<map>
    using namespace std;
    map<string,int>cnt;
    vector<string>words;
    //将单词s标准化 
    string repr(const string& s)//这个设计很巧妙 ,不改变原值 
    {
    string ans=s;
    for(int i=0;i<ans.size();i++)
    ans[i]=tolower(ans[i]);//大写字母转化为小写 
    sort(ans.begin(),ans.end());
    return ans;
    }
    int main()
    {
    int n=0;
    string s;
    while(cin>>s)
    {
    if(s[0]=='#')break;
    words.push_back(s);
    string r=repr(s);
    //cout<<r<<endl;
    if(!cnt.count(r))cnt[r]=0;//count()如果键值存在返回1,否则返回0;初始化键值对应的值 
    cnt[r]++;//计算出现的次数 类似数组的初始化 没出现过所以先初始化0 出现过map键值对应的count++
    
    }
    
    vector<string>ans;
    for(int i=0;i<words.size();i++)
    if(cnt[repr(words[i])]==1)ans.push_back(words[i]);//查map表,将符合条件的单词放进ans容器 
    sort(ans.begin(),ans.end());
    for(int i=0;i<ans.size();i++)
    cout<<ans[i]<<endl;
    return 0; 
    }
    

      

  • 相关阅读:
    在应用程序中利用Jena API处理OWL本体
    Encoded vs Literal, RPC vs Document
    DWR、XMLHTTP、XMLRPC和Flex
    北京的第一场雪
    让IE浏览器提示下载或直接打开word文档
    色拉英语第一集第一幕:记得说“请”
    色拉英语第一集第三幕:凯文在家吗?
    30天敏捷结果(30):提升敏捷结果
    生活:兔年春节家庭寻宝习俗
    敏捷个人:2011/1/26聊天记录(沟通、优势)
  • 原文地址:https://www.cnblogs.com/is-Tina/p/7350507.html
Copyright © 2020-2023  润新知