C++程式:檢查給定單詞是否符合給定模式


假設我們有一個模式p和一個字串str,我們需要檢查str是否遵循相同的模式。這裡的遵循是指模式中的一個字母和str中一個非空單詞之間存在雙射關係。

因此,如果輸入類似於pattern = "cbbc",str = "word pattern pattern word",則輸出為True。

為了解決這個問題,我們將遵循以下步驟:

  • strcin := str

  • 定義一個數組words

  • 對於strcin中的每個單詞

    • 將單詞插入到words的末尾

  • 定義一個對映p2i

  • i := 0

  • pat := 空字串

  • 對於pattern中的每個字元c:

    • 如果c不是p2i的成員,則:

      • (將i加1)

      • p2i[c] := i

    • pat := pat連線p2i[c]

  • 定義一個對映str2i

  • i := 0

  • pat1 := 空字串

  • 對於words中的每個單詞c:

    • 如果c不是str2i的成員,則:

      • (將i加1)

      • str2i[c] := i

    • pat1 := pat1連線str2i[c]

  • 當pat1與pat相同時返回true

示例

讓我們來看下面的實現,以便更好地理解:

線上演示

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool wordPattern( string pattern, string str ) {
      istringstream strcin(str);
      string word;
      vector<string> words;
      while (strcin >> word)
         words.push_back(word);
      unordered_map<char, int> p2i;
      int i = 0;
      string pat = "";
      for (auto c : pattern) {
         if (p2i.count(c) == 0) {
            i++;
            p2i[c] = i;
         }
         pat += to_string(p2i[c]);
      }
      unordered_map str2i;
      i = 0;
      string pat1 = "";
      for (auto c : words) {
         if (str2i.count(c) == 0) {
            i++;
            str2i[c] = i;
         }
         pat1 += to_string(str2i[c]);
      }
      return pat1 == pat;
   }
};
main(){
   Solution ob;
   cout << (ob.wordPattern("cbbc", "word pattern pattern word"));
}

輸入

"cbbc", "word pattern pattern word"

輸出

1

更新於:2020-12-22

392 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.