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

查找兄弟单词

时间:2020-03-24 22:57:12      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:相同   class   并且   size   push   int   name   include   turn   

输入描述:

先输入字典中单词的个数n

再输入n个单词作为字典单词

再输入一个单词,查找其在字典中兄弟单词的个数

再输入数字index索引第index个兄弟单词

3 abc bca cab abc 1

输出描述:

根据输入,输出查找到的兄弟单词的个数

将所有兄弟单词按照字典顺序排序,再输出第index个兄弟单词

2
bca

备注:

单词均由小写字母组成;相同单词不是兄弟单词。

考查:容器操作、泛型算法

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

//判断两个字符串是否是兄弟单词
int isBrother(string findString,string v)//值传递,不更改原字符串
{
    //将字符串排序后再比较是否相同
    sort(findString.begin(),findString.end());
    sort(v.begin(),v.end());
    if(findString==v)
        return 1;
    else
        return 0;
}

int main()
{
    int n,index;
    vector<string> words;//字典容器
    vector<string> bother;//兄弟单词容器
    string findWord;
    string cinWord;
    while(cin>>n)
    {
        words.clear();//每次重新来过都要清空容器
        bother.clear();
        for(int i=0; i<n; i++)
        {
            cin>>cinWord;
            words.push_back(cinWord);
        }
        cin>>findWord;
        cin>>index;
        for(int i=0; i<n; i++)
        {
            //若字典中第i个单词和findword不同,并且isBrother()返回1
            if(findWord!=words[i] && isBrother(findWord,words[i]))
            {
                bother.push_back(words[i]);//将第i个单词装入兄弟单词容器
            }
        }
        sort(bother.begin(),bother.end());//将兄弟单词容器排序
        cout<<bother.size()<<endl;
        if(index<=bother.size())
        {
            cout<<bother[index-1]<<endl;//输出第index个兄弟单词
        }
    }
    return 0;
}

C++11

 

查找兄弟单词

标签:相同   class   并且   size   push   int   name   include   turn   

原文地址:https://www.cnblogs.com/chongjz/p/12562677.html

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