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

#290 wordpattern

时间:2015-10-10 00:24:46      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:

#ifndef wordpattern_hpp
#define wordpattern_hpp

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

using namespace std;



class Solution {
public:
    bool wordPattern(string pattern, string str) {
        map<char, string> mcs;
        map<string, char> msc;
        stringstream ss{str};
        string item;
        for (auto c : pattern) {
            if(ss>>item){
                if(mcs.end() != mcs.find(c)) {
                    if (mcs[c] != item) {
                        return false;
                    }
                }else{
                    if(msc.end() != msc.find(item)){
                        return false;
                    }
                    mcs[c] = item;
                    msc[item] = c;
                }
            }else{
                return false;
            }
        }
        if(ss>>item)
            return false;
        return true;
    }
    void test(){
        struct wps{
            string pat;
            string str;
            bool res;
        };
        Solution s;
        vector<wps> tests{wps{"aaa","cat cat cat",true },
            wps{"abba","dog cat cat dog",true},
            wps{"abba","dog cat cat fish", false},
            wps{"aaaa","dog cat cat dog",false},
            wps{"abba","dog dog dog dog",false},
            wps{"aaa", "aa aa aa aa", false}};
        for (auto t : tests) {
            cout << "pattern: " << t.pat << ", str: \"" << t.str << "\" ";
            cout << ((t.res == s.wordPattern(t.pat, t.str)) ? "pass" : "fail") << \n;
        }
    }
};

#endif /* wordpattern_hpp */

程序使用了STL的map和vector,力求简明。

 

#290 wordpattern

标签:

原文地址:http://www.cnblogs.com/yuanqizhu/p/4865533.html

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