LeetCode刷题记录11——290. Word Pattern(easy)

目录

LeetCode刷题记录11——290. Word Pattern(easy)

题目

语言

思路

源码

后记


题目

LeetCode刷题记录11——290. Word Pattern(easy)

本题输入是两个字符串,输出是true或者false。计算过程为:依照字符串pattern的模板,去看字符串str的格式是否与pattern的相匹配,是则true,否则false。举个例子:有点类似小时候成语的格式一样:红红火火(aabb)、不了了之(abba)……。这题类似:abba->dog cat cat dog。

语言

java

LeetCode刷题记录11——290. Word Pattern(easy)

思路

并行查看模式和字符串,比较他们最后出现的索引。使用map创建一个对象mymap,使用mymap.put的方法,该方法的意思应该是:如果第二次put进同样的key不同value,返回的值是被挤掉的那个value!不然就是null。

源码

public boolean wordPattern(String pattern, String str) {
    String[] words = str.split(" ");
    if (words.length != pattern.length())
        return false;
    Map mymap = new HashMap();
    for (Integer i=0; i<words.length; ++i)
        if (mymap.put(pattern.charAt(i), i) != mymap.put(words[i], i))
            return false;
    return true;
}

后记

此题方法借鉴于Stefan Pochmann大神的思路,具体可看Stefan Pochmann大神的原话

相关文章:

  • 2021-07-05
  • 2021-09-16
  • 2021-12-28
  • 2021-04-28
  • 2022-12-23
  • 2021-10-29
猜你喜欢
  • 2021-04-27
  • 2022-02-16
  • 2021-12-02
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-03
相关资源
相似解决方案