zoukankan      html  css  js  c++  java
  • [LeetCode]Word Pattern

    题目描述:(链接

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

    Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

    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:
    You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

    解题思路:

    找到字符和字符串之间的映射关系就行了,用两个哈希表分别存放<字符,字符串>和<字符串, 字符>的映射关系,前提需要分解字符串(split函数)。

     1 class Solution {
     2 public:
     3     bool wordPattern(string pattern, string str) {
     4         unordered_map<char, string> cache1;
     5         unordered_map<string, char> cache2;
     6         
     7         vector<string> splitStrs = split(str, ' ');
     8         
     9         if (splitStrs.size() != pattern.size()) {
    10             return false;
    11         }
    12         
    13         for (size_t i = 0; i < pattern.size(); ++i) {
    14             if (cache1.find(pattern[i]) == cache1.end() && cache2.find(splitStrs[i]) == cache2.end()) {
    15                 cache1[pattern[i]] = splitStrs[i];
    16                 cache2[splitStrs[i]] = pattern[i];
    17             } else if (cache1.find(pattern[i]) != cache1.end() && cache2.find(splitStrs[i]) != cache2.end()){
    18                 if (cache1[pattern[i]] != splitStrs[i] && cache2[splitStrs[i]] != pattern[i]) {
    19                     return false;
    20                 }
    21             } else {
    22                 return false;
    23             }
    24         }
    25         
    26         return true;
    27     }
    28 private:
    29     vector<string> split(const string& src, char sep) {
    30         vector<string> result;
    31         size_t lastIndex = 0;
    32         size_t index = 0;
    33         while ((index = src.find(sep, lastIndex)) != string::npos) {
    34             result.push_back(src.substr(lastIndex, index - lastIndex));
    35             lastIndex = index + 1;
    36         }
    37         
    38         string lastStr = src.substr(lastIndex);
    39         if (!lastStr.empty()) {
    40             result.push_back(lastStr);
    41         }
    42         
    43         return result;
    44     }
    45 };
  • 相关阅读:
    [spring]AOP(切面)编程
    [spring]基于注解的spring配置
    [redis]redis五种数据类型和应用场景
    [redis]redis实现分页的方法
    [zookeeper]ZooInspector的使用
    [log4j]SLF4J+log4j的使用
    [zookeeper]依赖jar的问题
    导出word功能,用html代码在word中插入分页符
    jq实现千分位的转换
    oracle 创建表空间及oracle 11g表空间之最大最小
  • 原文地址:https://www.cnblogs.com/skycore/p/4869150.html
Copyright © 2011-2022 走看看