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

    Problem Description:

    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 substring in str.

    Examples:

      1. pattern = "abab", str = "redblueredblue" should return true.
      2. pattern = "aaaa", str = "asdasdasdasd" should return true.
      3. pattern = "aabb", str = "xyzabcxzyabc" should return false. 

    Notes:
    You may assume both pattern and str contains only lowercase letters.


    The problem becomes much more difficult after the spaces are removed. Now we need to determine which part matchs which part by ourselves. This post shares a very clear solution in Java, which is rewritten below in C++.

     1 class Solution {
     2 public:
     3     bool wordPatternMatch(string pattern, string str) {
     4         unordered_set<string> st;
     5         unordered_map<char, string> mp;
     6         return match(str, 0, pattern, 0, st, mp);
     7     }
     8 private:
     9     bool match(string& str, int i, string& pat, int j, unordered_set<string>& st, unordered_map<char, string>& mp) {
    10         int m = str.length(), n = pat.length();
    11         if (i == m && j == n) return true;
    12         if (i == m || j == n) return false;
    13         char c = pat[j];
    14         if (mp.find(c) != mp.end()) {
    15             string s = mp[c];
    16             int l = s.length();
    17             if (s != str.substr(i, l)) return false;
    18             return match(str, i + l, pat, j + 1, st, mp);
    19         } 
    20         for (int k = i; k < m; k++) {
    21             string s = str.substr(i, k - i + 1);
    22             if (st.find(s) != st.end()) continue;
    23             st.insert(s);
    24             mp[c] = s;
    25             if (match(str, k + 1, pat, j + 1, st, mp)) return true;
    26             st.erase(s);
    27             mp.erase(c);
    28         }
    29         return false;
    30     }
    31 };
  • 相关阅读:
    java 数组的基本概念
    java 简单类
    python3 爬虫教学之爬取链家二手房(最下面源码) //以更新源码
    python3 爬虫之爬取安居客二手房资讯(第一版)
    python3 怎么统计英文文档常用词?(附解释)
    python3 怎么爬取新闻网站?
    ASP.NET 线程详解
    EF6 对于实体字段类型转换扩展
    mysql之调优概论
    mysql8之与标准sql的区别
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4870514.html
Copyright © 2011-2022 走看看