华为OJ:查找兄弟单词

 

 

 

输入描述:

先输入字典中单词的个数,再输入n个单词作为字典单词。
输入一个单词,查找其在字典中兄弟单词的个数
再输入数字n

输出描述:

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

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

int isBrother(string s1, string s2)
{
    if (s1.size() != s2.size())
        return 0;
    if (s1==s2)
        return 0;
    int flag = 0;
    /*
    sort(s1.begin(), s1.end());
    sort(s2.begin(), s2.end());
    if(s1 == s2)
        return 1;
    else
        return 0;
    */
    
    for(int i=0; i<s2.size(); i++)
    {
        flag = 0;
        if(s1.find(s2[i]) == string::npos)
        {
            flag = 0;
            break;
        }
        else
        {
            s1.erase(s1.find(s2[i]),1);
            flag = 1;
        }
    }
    return flag;
    
}
int main()
{
    int n;
    while(cin>>n)
    {
        string s;
        vector<string> sd;
        for(int i = 0; i < n; i++)
        {
            cin >> s;
            sd.push_back(s);
        }
        sort(sd.begin(), sd.end());
        cin >> s;
        cin >> n;
        vector<string> bvec;
        vector<string>::iterator it = sd.begin();
        int count = 0;
        string res;
        for(; it != sd.end(); it++)
        {
            if(isBrother(*it, s))
            {
                count++;
                if(count == n)
                    res = *it;
            }
        }
        cout << count << '\n';
        //printf("%d\n", count);
        if (count >= n)   // 这句话一定要加,不加不通过测试(不知道为什么) 
            cout << res << endl;
            //printf("%s\n", res.c_str());
    }
    return 0;
}

上述程序包含两种方法:

一种简单粗暴,对每一个单词进行重排序,利用sort()函数完成string对象的(程序要包含头文件#include <algorithm>)

第二种,看子程序isBrother()

猜你喜欢

转载自blog.csdn.net/Doutd_y/article/details/82424692