计算两个字符串链表中的共同数据项,需要考虑重复选项的情况

Problem
/*
// Given two lists of strings build a new list that has all strings that appear in both the original lists. If the same string appears more than once output it as many times as it appears in both lists 
// 
// Example: 
// "dog", "bird", "elephant", "dog", "dog", "cat" 
// "cat", "dog", "dog", "cat", "cat", "fish" 
// Result (order doesn't matter) 
// "dog", "dog", "cat"

*/

Solution
#include <iostream>
#include <list>
#include <iterator>
#include <algorithm>
#include <string>

using namespace std;

void find_comm_strings(list<string>& output, list<string>& listA, list<string>& listB)
{
    listA.sort();
    listB.sort();

    list<string>::const_iterator citA = listA.begin();
    list<string>::const_iterator citB = listB.begin();

    while(citA != listA.end() && citB != listB.end()){
        int eq = (*citA).compare(*citB);
        if(eq == 0){
            output.push_back(*citA);
            citA ++;
            citB ++;
        }
        else if (eq > 0){
            citB ++;
        }
        else{
            citA ++;
        }
    }
}

int main(int argc, char* argv[])
{
    list<string> listA;
    list<string> listB;
    list<string> output;

    cout << "list A:" << endl;
    listA.push_back("dog");
    listA.push_back("bird");
    listA.push_back("elephant");
    listA.push_back("dog");
    listA.push_back("dog");
    listA.push_back("cat");
    copy(listA.begin(), listA.end(), ostream_iterator<string>(cout, ","));
    cout << endl;

    cout << "list B:" << endl;
    listB.push_back("cat");
    listB.push_back("dog");
    listB.push_back("dog");
    listB.push_back("cat");
    listB.push_back("cat");
    listB.push_back("fish");
    copy(listB.begin(), listB.end(), ostream_iterator<string>(cout, ","));
    cout << endl;

    find_comm_strings(output, listA, listB);

    cout << "common strings" << endl;
    copy(output.begin(), output.end(), ostream_iterator<string>(cout, ","));
    cout << endl;

 return 0;
}

Output
list A:
dog,bird,elephant,dog,dog,cat,
list B:
cat,dog,dog,cat,cat,fish,
common strings
cat,dog,dog,
Press any key to continue . . .


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值