单词重排

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

#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <algorithm>  
using namespace std;

map<string, int> cnt;  //以标准化后的单词为key, 以value的个数作为单词key出现的次数 
vector<string> words;  //保存输入的单词 

string repr(string s){//将单词标准化,即将单词全部转为小写字母后,再进行排序 
    for(int i=0; i<s.length(); i++){
        s[i] = tolower(s[i]);  //将第i个字母转化为小写字母,tolower()功能是把字母字符转换成小写,非字母字符不做出处理 
    }
    sort(s.begin(), s.end());  
    return s;
}

int main(){
    int n =0; 
    string s;
    while(cin>>s){   
        if(s[0]=='#') break;
        words.push_back(s);  //将输入的单词放进容器words中 
        string r=repr(s);  //将单词标准化 
        cnt[r] ++; 
    }
    vector<string> ans; //保存满足要求的单词 
    for(int i=0; i<words.size(); i++)
    {  
        if(cnt[repr(words[i])] ==1 ) 
        {  //如果这个单词标准化后作为cnt的key,看对应的value值是否为1,如果为1,则说明该单词不能通过字母重排得到文本中的另外一个单词 
            ans.push_back(words[i]);  // 将符合要求的单词放进ans中 
        }
    }
    sort(ans.begin(), ans.end());   
    for(int i=0; i<ans.size(); i++){
        cout<<ans[i]<<endl;  
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40835329/article/details/81624498
今日推荐