LeetCode 290. Word Pattern

来源:互联网 发布:安卓软件商店 编辑:程序博客网 时间:2024/06/08 12:34

Given a pattern and a string str, find if str follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

Examples:

  1. pattern = "abba", str = "dog cat cat dog" should return true.
  2. pattern = "abba", str = "dog cat cat fish" should return false.
  3. pattern = "aaaa", str = "dog cat cat dog" should return false.
  4. pattern = "abba", str = "dog dog dog dog" should return false.

Notes:

You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

C++没有split真不方便,去网上找了分割字符串的方法,第一次知道strtok()函数。

class Solution {public:    vector<string> split(string str){        char* cstr;        cstr = new char[str.size() + 1];        strcpy(cstr, str.c_str());        vector<string> res;        char* p;        p = strtok(cstr, " ");        while(p){            res.push_back(p);            p = strtok(NULL, " ");        }        return res;    }    bool wordPattern(string pattern, string str) {        vector<string> pat = split(str);        if(pattern.size() != pat.size()) return false;        map<char, string> m1;        map<string, char> m2;        map<char, string>::iterator it1;        map<string, char>::iterator it2;        int i, len;        len = pattern.size();        for(i = 0; i < len; i ++){                        it1 = m1.find(pattern[i]);            if(it1 == m1.end()){                m1[pattern[i]] = pat[i];            }else{                if(m1[pattern[i]] != pat[i]) return false;            }                        it2 = m2.find(pat[i]);            if(it2 == m2.end()){                m2[pat[i]] = pattern[i];            }else{                if(m2[pat[i]] != pattern[i]) return false;            }        }        return true;    }};


0 0
原创粉丝点击