[抄题]:
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
.
Examples:
- pattern =
"abba"
, str ="dog cat cat dog"
should return true. - pattern =
"abba"
, str ="dog cat cat fish"
should return false. - pattern =
"aaaa"
, str ="dog cat cat dog"
should return false. - pattern =
"abba"
, str ="dog dog dog dog"
should return false.
Notes:
You may assume pattern
contains only lowercase letters, and str
contains lowercase letters separated by a single space.
[暴力解法]:
时间分析:
空间分析:
[优化后]:
时间分析:
空间分析:
[奇葩输出条件]:
[奇葩corner case]:
二者匹配的问题,不是2*2的空不空,而是二者长度是否相等
[思维问题]:
忘了分离单词怎么写了
[一句话思路]:
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
hashmap两次输入的类型不一致,可以不写类型,直接丢掉<>尖括号
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
[总结]:
hashmap存同样的值,返回值不同
[复杂度]:Time complexity: O(n) Space complexity: O(n)
[英文数据结构或算法,为什么不用别的数据结构或算法]:
hashmap存同样的值,返回值不同:
import java.util.HashMap; import java.util.Map; public class Test { public static void main(String[] args) { Map<String, String> map = new HashMap<String, String>(); String p1 = map.put("11", "22"); System.out.println("p1:" + p1); String p2 = map.put("33", "44"); System.out.println("p2:" + p2); String value1 = map.get("11"); System.out.println("value1:" + value1); String p3 = map.put("11", "44"); System.out.println("p3:" + p3); String value2 = map.get("11"); System.out.println("value2:" + value2); } } p1:null p2:null value1:22 p3:22 value2:44
[关键模板化代码]:
[其他解法]:
[Follow Up]:
[LC给出的题目变变变]:
291. Word Pattern II 没有空格,回溯法?
[代码风格] :
class Solution { public boolean wordPattern(String pattern, String str) { String[] words = str.split(" "); if (words.length != pattern.length()) return false; Map index = new HashMap(); for (Integer i=0; i<words.length; ++i) if (index.put(pattern.charAt(i), i) != index.put(words[i], i)) return false; return true; } }