• 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 };
  • 相关阅读:
    精选微软经典的算法面试100题
    C++高效程序设计
    算法导论第五章:概率分析和随机算法
    算法导论第六章:堆排序
    算法导论第八章:线性时间排序
    算法导论第六章:堆排序
    算法导论第七章:快速排序
    M0n0wall安装及配置教程(上)
    ASP.NET十分有用的页面间传值方法
    PC网络配置切换脚本(IP地址切换脚本)
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4859490.html
Copyright © 2020-2023  润新知