Leetcode 291: Word Pattern II

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.

 

 1 public class Solution {
 2     public bool WordPatternMatch(string pattern, string str) {
 3         return IsMatch(pattern, str, 0, 0, new Dictionary<char, string>(), new HashSet<string>());
 4     }
 5     
 6     private bool IsMatch(string pattern, string str, int pStart, int sStart, Dictionary<char, string> map, HashSet<string> hashset)
 7     {
 8         if (pStart >= pattern.Length || sStart >= str.Length)
 9         {
10             return pStart >= pattern.Length && sStart >= str.Length;
11         }
12         
13         if (map.ContainsKey(pattern[pStart]))
14         {
15             var s = map[pattern[pStart]];
16             if (!str.Substring(sStart, str.Length - sStart).StartsWith(s))
17             {
18                 return false;
19             }
20             
21             return IsMatch(pattern, str, pStart + 1, sStart + s.Length, map, hashset);
22         }
23         else
24         {
25             for (int i = sStart; i < str.Length; i++)
26             {
27                 var s = str.Substring(sStart, i - sStart + 1);
28                 
29                 if (!hashset.Contains(s))
30                 {
31                     hashset.Add(s);
32                     map[pattern[pStart]] = s;
33                     
34                     if (IsMatch(pattern, str, pStart + 1, i + 1, map, hashset))
35                     {
36                         return true;
37                     }
38                     
39                     hashset.Remove(s);
40                     map.Remove(pattern[pStart]);
41                 }
42             }
43         }
44         
45         return false;
46     }
47 }

 

posted @ 2017-12-20 06:17  逸朵  阅读(154)  评论(0编辑  收藏  举报