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; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/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...
閱讀 2951·2021-11-25 09:43
閱讀 3327·2021-11-24 09:39
閱讀 2828·2021-09-22 15:59
閱讀 2174·2021-09-13 10:24
閱讀 509·2019-08-29 17:02
閱讀 2098·2019-08-29 13:23
閱讀 3058·2019-08-29 13:06
閱讀 3539·2019-08-29 13:04