Problem
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.
Example 1:
Input: pattern = "abab", str = "redblueredblue"
Output: true
Example 2:
Input: pattern = pattern = "aaaa", str = "asdasdasdasd"
Output: true
Example 3:
Input: pattern = "aabb", str = "xyzabcxzyabc"
Output: false
Notes:
You may assume both pattern and str contains only lowercase letters.
class Solution { public boolean wordPatternMatch(String pattern, String str) { if (pattern == null || str == null || str.length() < pattern.length()) return false; Mapmap = new HashMap<>(); return helper(pattern, 0, str, 0, map); } private boolean helper(String pattern, int i, String str, int j, Map map) { if (i == pattern.length() && j == str.length()) return true; if (i == pattern.length() || j == str.length()) return false; char ch = pattern.charAt(i); if (map.containsKey(ch)) { String s = map.get(ch); if (!str.substring(j).startsWith(s)) return false; else return helper(pattern, i+1, str, j+s.length(), map); } else { //try put some str substrings into the map for (int k = j; k < str.length(); k++) { String part = str.substring(j, k+1); if (map.containsValue(part)) continue; //already used by a different key //add the new pair, dfs, remove the new pair (backtracking) map.put(ch, part); if (helper(pattern, i+1, str, k+1, map)) return true; map.remove(ch); } } return false; } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/72245.html
摘要:如果出现过,必须映射必须唯一。如果映射正确,不断尝试,返回可能的情况,有一种情况成立,就是全局成立。 pattern = abab, str = redblueredblue should return true. pattern = aaaa, str = asdasdasdasd should return true. pattern = aabb, str = xyzabcxzy...
摘要:哈希表法复杂度时间空间思路这题几乎和一模一样,不同的就是之前是字母映射字母,现在是字母映射字符串而已。 Word Pattern Given a pattern and a string str, find if str follows the same pattern. Examples: pattern = abba, str = dog cat cat dog should r...
摘要:月下半旬攻略道题,目前已攻略题。目前简单难度攻略已经到题,所以后面会调整自己,在刷算法与数据结构的同时,攻略中等难度的题目。 Create by jsliang on 2019-07-30 16:15:37 Recently revised in 2019-07-30 17:04:20 7 月下半旬攻略 45 道题,目前已攻略 100 题。 一 目录 不折腾的前端,和咸鱼有什么区别...
摘要:在线网站地址我的微信公众号完整题目列表从年月日起,每天更新一题,顺序从易到难,目前已更新个题。这是项目地址欢迎一起交流学习。 这篇文章记录我练习的 LeetCode 题目,语言 JavaScript。 在线网站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公众号: showImg(htt...
Problem Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the l...
阅读 2950·2021-11-25 09:43
阅读 3326·2021-11-24 09:39
阅读 2827·2021-09-22 15:59
阅读 2173·2021-09-13 10:24
阅读 509·2019-08-29 17:02
阅读 2098·2019-08-29 13:23
阅读 3057·2019-08-29 13:06
阅读 3538·2019-08-29 13:04