• [LeetCode] Word Pattern


    Word Pattern

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

    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:

    1. Both pattern and str contains only lowercase alphabetical letters.
    2. Both pattern and str do not have leading or trailing spaces.
    3. Each word in str is separated by a single space.
    4. Each letter in pattern must map to a word with length that is at least 1.

    Credits:
    Special thanks to @minglotus6 for adding this problem and creating all test cases.

     1 class Solution {
     2 public:
     3     bool wordPattern(string pattern, string str) {
     4         vector<string> dic;
     5         istringstream sin(str);
     6         string tmp;
     7         while (sin >> tmp) dic.push_back(tmp);
     8         if (dic.size() != pattern.size()) return false;
     9         unordered_map<char, string> mp1;
    10         unordered_map<string, char> mp2;
    11         for (int i = 0; i < pattern.size(); ++i) {
    12             if (mp1.find(pattern[i]) == mp1.end()) {
    13                 mp1[pattern[i]] = dic[i];
    14             } else if (mp1[pattern[i]] != dic[i]) {
    15                 return false;
    16             }
    17             if (mp2.find(dic[i]) == mp2.end()) {
    18                 mp2[dic[i]] = pattern[i];
    19             } else if (mp2[dic[i]] != pattern[i]) {
    20                 return false;
    21             }
    22         }
    23         return true;
    24     }
    25 };
  • 相关阅读:
    053467
    053466
    053465
    NC201613 Jelly
    NC14608 after与迷宫
    NC14572 走出迷宫
    340. 通信线路
    1135. 新年好
    903. 昂贵的聘礼
    P5767 [NOI1997]最优乘车
  • 原文地址:https://www.cnblogs.com/easonliu/p/4856850.html
Copyright © 2020-2023  润新知