算法竞赛入门 5.3.2 字母重排

本文介绍如何使用C++的vector和sort函数保存并排序字典中的单词,然后通过匹配和遍历来查找特定单词。包括实现细节、运行错误处理及代码优化。

重点:

1.用vector保存字典单词;

2.用sort函数对字典单词排序;

3.匹配每个单词,遍历一次字典(可以对字典的单词和查找单词按字符排序,或者用map统计每个字符出现的次数间接比较大小)


遗留问题:???

第24行代码改为:

for(vector<string>::size_type i = dicLength-1 ; i>=0 ; i--){

程序会发生运行错误,觉得代码没错。。。



代码如下:

#include <iostream>
#include <vector>
#include <map>
#include <stdio.h>
#include <algorithm>

using namespace std;

int main()
{
    freopen("test.in","r",stdin);
//    freopen("test.in",stdin);
    vector<string> dic;
    string s;

    while((cin >> s) && s != "******"){
        dic.push_back(s);
    }
    sort(dic.begin() ,dic.end());

    while(cin >> s){
        int first = 1;
        int dicLength = dic.size();
        for(vector<string>::size_type i = 0 ; i<dicLength ; i++){
            string temps = dic[i];
//            cout << dicLength-1 << " " << i <<" " << temps << endl;
            map<char,int> counter1,counter2;

            if(temps.length() == s.length()){
                for(string::size_type j=0 ; j<temps.length() ; j++){
                    counter1[temps[j]]++;
                    counter2[s[j]]++;
                }
            }
            if(counter1 == counter2 && counter1.size()!=0){
                if(first == 1){
                    cout << temps;
                    first = 0;
                }
                else{
                    cout << " " << temps;
                }
            }

        }
        if(first == 1){//not find
            cout << ":(";
        }
        cout << endl;
    }

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值