1. 程式人生 > >leetcode刷題,總結,記錄,備忘 290

leetcode刷題,總結,記錄,備忘 290

leetcode290 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:

  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.

使用2個map,做兩兩對映。每個字母和單詞分別對應相應的字母和單詞,在map中沒有該鍵的時候進行新增,在map中已經有鍵的時候進行檢驗,是否相同。
class Solution {
public:
	bool wordPattern(string pattern, string str) {
		vector<string> vs;

		while (1)
		{
			int pos = str.find(" ");
			if (pos == string::npos)
			{
				vs.push_back(str);
				break;
			}
			else
			{
				vs.push_back(str.substr(0, pos));
				str = str.substr(pos + 1);
			}
		}

		if (vs.size() != pattern.size())
		{
			return false;
		}

		map<string, string> ms;
		map<string, string> ms2;
		for (int i = 0; i < pattern.size(); ++i)
		{
			string t;
			t += pattern[i];
			if (ms.find(t) == ms.end() && ms2.find(vs[i]) == ms2.end())
			{
				ms[t] = vs[i];
				ms2[vs[i]] = t;
			}
			else
			{
				if (ms[t] != vs[i] || ms2[vs[i]] != t)
				{
					return false;
				}
			}
		}

		return true;
	}
};