资讯专栏INFORMATION COLUMN

291. Word Pattern II

el09xccxy / 545人阅读

摘要:如果出现过,必须映射必须唯一。如果映射正确,不断尝试,返回可能的情况,有一种情况成立,就是全局成立。

pattern = "abab", str = "redblueredblue" should return true.
pattern = "aaaa", str = "asdasdasdasd" should return true.
pattern = "aabb", str = "xyzabcxzyabc" should return false.
public class Solution {
    public boolean wordPatternMatch(String pattern, String str) {
        HashMap map = new HashMap<>();
        Set set = new HashSet<>();
        return match(pattern, 0, str, 0, map, set);
    }
    
    public boolean match(String pattern, int i, String str, int j, HashMap map, Set set){
        // base case
        if(i == pattern.length() && j == str.length()) return true;
        if(i == pattern.length() || j == str.length()) return false;
        
        // 如果pattern出现过,必须char,pattern映射必须唯一。
        // 如果映射正确,go deeper
        Character c = pattern.charAt(i);
        if(map.containsKey(c)){
            String s = map.get(c);
            if(!str.startsWith(s, j)){
                return false;
            }
            return match(pattern, i+1, str, j+s.length(), map, set);
        }
        
        // 不断尝试pattern,返回可能的情况,有一种情况成立,就是全局成立。
        for(int k=j; k           
               
                                           
                       
                 

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/66948.html

相关文章

  • [LeetCode] 291. Word Pattern II

    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 ...

    genefy 评论0 收藏0
  • [Leetcode] Word Pattern 单词模式

    摘要:哈希表法复杂度时间空间思路这题几乎和一模一样,不同的就是之前是字母映射字母,现在是字母映射字符串而已。 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...

    wdzgege 评论0 收藏0
  • 前端 | 每天一个 LeetCode

    摘要:在线网站地址我的微信公众号完整题目列表从年月日起,每天更新一题,顺序从易到难,目前已更新个题。这是项目地址欢迎一起交流学习。 这篇文章记录我练习的 LeetCode 题目,语言 JavaScript。 在线网站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公众号: showImg(htt...

    张汉庆 评论0 收藏0
  • LeetCode 攻略 - 2019 年 7 月下半月汇总(100 题攻略)

    摘要:月下半旬攻略道题,目前已攻略题。目前简单难度攻略已经到题,所以后面会调整自己,在刷算法与数据结构的同时,攻略中等难度的题目。 Create by jsliang on 2019-07-30 16:15:37 Recently revised in 2019-07-30 17:04:20 7 月下半旬攻略 45 道题,目前已攻略 100 题。 一 目录 不折腾的前端,和咸鱼有什么区别...

    tain335 评论0 收藏0
  • [LeetCode] 244. Shortest Word Distance II

    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...

    Nekron 评论0 收藏0

发表评论

0条评论

el09xccxy

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<