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 };
  • 相关阅读:
    AIoT 2020 年分析
    TensorFlow解析常量、变量和占位符
    TensorFlow编程结构
    对端边缘云网络计算模式:透明计算、移动边缘计算、雾计算和Cloudlet
    Harmony生命周期
    立体显示与BCN双稳态手性向列相
    显示技术示例
    SystemML大规模机器学习,优化算子融合方案的研究
    改天有空看看 1
    gradle 123123
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4859490.html
Copyright © 2011-2022 走看看