zoukankan      html  css  js  c++  java
  • 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. patterncontains only lowercase alphabetical letters, and str contains words separated by a single space. Each word in str contains only lowercase alphabetical letters.
    2. Both pattern and str do not have leading or trailing spaces.
    3. Each letter in pattern must map to a word with length that is at least 1.

    Runtime: 0ms

     1 class Solution {
     2 public:
     3     bool wordPattern(string pattern, string str) {
     4         if(pattern.empty() && str.empty()) return true;
     5         if(pattern.empty() || str.empty()) return false;
     6         
     7         unordered_map<char, string> p2s;
     8         unordered_map<string, char> s2p;
     9         
    10         vector<string> vec;
    11         int start = 0, end = 0;
    12         while(end < str.size()){
    13             while(end < str.size() && str[end] != ' ')
    14                 end++;
    15             vec.push_back(str.substr(start, end - start));
    16             start = end + 1;
    17             end = start;
    18         }
    19         
    20         if(pattern.length() != vec.size()) return false;
    21         
    22         for(int i = 0; i < pattern.size(); i++){
    23             if(p2s.find(pattern[i]) == p2s.end())
    24                 p2s[pattern[i]] = vec[i];
    25             else
    26                 if(p2s[pattern[i]] != vec[i]) return false;
    27                 
    28             if(s2p.find(vec[i]) == s2p.end())
    29                 s2p[vec[i]] = pattern[i];
    30             else
    31                 if(s2p[vec[i]] != pattern[i]) return false;
    32         }
    33         return true;
    34     }
    35 };
  • 相关阅读:
    第七章习题G题
    第二周习题O题
    P4735 最大异或和
    P3008 [USACO11JAN]道路和飞机Roads and Planes
    P4009 汽车加油行驶问题
    P1073 最优贸易
    P2260 [清华集训2012]模积和
    P2865 [USACO06NOV]路障Roadblocks
    P1821 [USACO07FEB]银牛派对Silver Cow Party
    P4180 【模板】严格次小生成树[BJWC2010]
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4859490.html
Copyright © 2011-2022 走看看