首页 > 其他 > 详细

#290 wordpattern

时间:2015-10-10 00:24:42      阅读:293      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!