zoukankan      html  css  js  c++  java
  • [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 };
  • 相关阅读:
    Django知识总结(一)
    Django知识总结(二)
    Django知识总结(三)
    机器学习领域主要术语的英文表达
    Python的进程与线程--思维导图
    MySQL数据库--思维导图
    5.18 每日小三练
    5.14 每日小三练
    5.12 每日小三练
    5.9 每日小三练
  • 原文地址:https://www.cnblogs.com/easonliu/p/4856850.html
Copyright © 2011-2022 走看看