1. 程式人生 > >[Leetcode ]290. Word Pattern

[Leetcode ]290. Word Pattern

  1. Word Pattern
    Easy

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.

Example 1:

Input: pattern = “abba”, str = “dog cat cat dog”
Output: true
Example 2:

Input:pattern = “abba”, str = “dog cat cat fish”
Output: false
Example 3:

Input: pattern = “aaaa”, str = “dog cat cat dog”
Output: false
Example 4:

Input: pattern = “abba”, str = “dog dog dog dog”
Output: false
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

給定一種 pattern(模式) 和一個字串 str ,判斷 str 是否遵循相同的模式。

這裡的遵循指完全匹配,例如, pattern 裡的每個字母和字串 str 中的每個非空單詞之間存在著雙向連線的對應模式。

示例1:

輸入: pattern = “abba”, str = “dog cat cat dog”
輸出: true
示例 2:

輸入:pattern = “abba”, str = “dog cat cat fish”
輸出: false
示例 3:

輸入: pattern = “aaaa”, str = “dog cat cat dog”
輸出: false
示例 4:

輸入: pattern = “abba”, str = “dog dog dog dog”
輸出: false
說明:
你可以假設 pattern 只包含小寫字母, str 包含了由單個空格分隔的小寫字母。

解題思路:此題和205同構字串是同一個套路。
理由hash表,把字元和字串相互對映,然後判斷。
程式碼:
class Solution {
public:
bool wordPattern(string pa, string str) {

    if(pa.size() ==0 || str.length() == 0 ) return false;       
  
unordered_map < char ,string > ch;
unordered_map < string ,char> s;       
vector <string> re(pa.size());        
int j=0;               
    
for( int  i = 0; i < pa.size(); i++)
    {
        if(j>=str.length())return false; // pattern字元數比str中的單詞數多。
        while( j < str.length() ) //把某個單詞讀取出來
        {
            if (str[j] != ' ')
            {
                re[i]+=str[j];
                 j++;
            }
            else
            {
                j++;
                break;
            }
        }
         if(ch.count(pa[i]) && s.count(re[i]) )
         {
             if(ch[pa[i]] != re[i])
                 return false;                     
         }
          else if (ch.count(pa[i]) || s.count(re[i]) )
                    return false;
                else {                  
                        ch[pa[i]] = re[i];
                       s[re[i]] = pa[i];
                    }          
       }
    if (j < str.length()) return false; //str中的單詞數比pattern中的字元多。
    
    return true;
}

};