leetcode 290: Word Pattern

問題描述:

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:
pattern = “abba”, str = “dog cat cat dog” should return true.
pattern = “abba”, str = “dog cat cat fish” should return false.
pattern = “aaaa”, str = “dog cat cat dog” should return false.
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.

思路:

首先把str給分割成單詞數組,然後用笨方法,保存雙向映射,這就是爲什麼代碼中設置兩個map。遍歷數組,用map來查找和插入映射。

代碼:

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        //split into word list
        vector<string> wordlist;
        string::size_type pos;
        str += " ";
        int size = str.size();
        for (int i = 0; i < size; i++)
        {
            pos = str.find(" ", i);  //find the space position
            if (pos < size)
            {
                string word = str.substr(i, pos - i); //extract the word
                if (word != "") //record the word
                {
                    wordlist.push_back(word);
                }
                i = pos;
            }
        }
        int w_size = wordlist.size();
        int p_size = pattern.size();
        if (w_size != p_size) return false;
        map<char, string> c2s_mapped;  //map char to string
        map<string, char> s2c_mapped;  //map string to char
        for (int i = 0; i < p_size; i++)
        {
            char c_now = pattern[i];
            string s_now = wordlist[i];
            map<char, string>::iterator it_c2s = c2s_mapped.find(c_now);
            if (it_c2s != c2s_mapped.end())  //found
            {
                if (it_c2s->second != s_now) return false;
            }
            else  //not found
            {
                map<string, char>::iterator it_s2c = s2c_mapped.find(s_now);
                if (it_s2c != s2c_mapped.end()) return false;

                c2s_mapped.insert(pair<char, string>(c_now, s_now));
                s2c_mapped.insert(pair<string, char>(s_now, c_now));
            }
        }
        return true;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章