leetcode Word Pattern题解

本文深入探讨了模式匹配算法,通过具体实例展示了如何判断两个字符串是否遵循相同的模式。文章提供了详细的解题思路,包括使用HashMap进行字符和单词位置的映射,并比较两者的模式一致性。

题目描述:

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

Example 1:

Input: pattern = "abba", str = "dog cat cat dog"
Output: true

Example 2:

Input:pattern = "abba", str = "dog cat cat fish"
Output: false

Example 3:

Input: pattern = "aaaa", str = "dog cat cat dog"
Output: false

Example 4:

Input: pattern = "abba", str = "dog dog dog dog"
Output: false

中文理解:给出两个字符串,其中一个由不含空格的a-z的字符组成为pattern,一个有空格分割组成的字符串s,判断这两个字符是否是相同的模式,相同模式的含义是:pattern的相同字符出现的位置,s中相同位置出现的字符串也要相同。

解题思路:首先HashMap<Character,String> map=new HashMap<Character,String>();使用map来存放pattern中相同字符出现的下标构成字符串,再HashMap<String,String> map1=new HashMap<String,String>();使用map1来存放s中相同字符串出现的下标构成的字符串,最后比较map1和map的values是否相同。

代码(java):

class Solution {
    public boolean wordPattern(String pattern, String str) {
        HashMap<Character,String> map=new HashMap<Character,String>();
        for(int i=0;i<pattern.length();i++){
            if(map.keySet().contains(pattern.charAt(i))){
                String tmp=map.get(pattern.charAt(i));
                tmp+=i;
                map.put(pattern.charAt(i),tmp);
            }
            else{
                String tmp="";
                tmp+=i;
                map.put(pattern.charAt(i),tmp);
            }
        }
        String []strSplit=str.split(" ");
        HashMap<String,String> map1=new HashMap<String,String>();
        for(int i=0;i<strSplit.length;i++){
            if(map1.keySet().contains(strSplit[i])){
                String tmp=map1.get(strSplit[i]);
                tmp+=i;
                map1.put(strSplit[i],tmp);
            }
            else{
                String tmp="";
                tmp+=i;
                map1.put(strSplit[i],tmp);
            }
        }
        return map.values().size()==map1.values().size() && map.values().containsAll(map1.values());
    }
}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值