leetcode Word Pattern
Given a
pattern
and a stringstr
, find ifstr
follows the same pattern.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:
- Both
pattern
andstr
contains only lowercase alphabetical letters.- Both
pattern
andstr
do not have leading or trailing spaces.- Each word in
str
is separated by a single space.- Each letter in
pattern
must map to a word with length that is at least 1.
题目地址: leetcode Word Pattern
题意:
给定一个模式串和一个字符串,判断模式串是否符合字符串的描述。
如,
模式串为abba ,字符串为dog cat cat dog 返回true
模式串为abba ,字符串为dog cat cat fish 返回false
- 模式串和字符串只有小写字母,开头和结尾都没有多余的字符
- 在字符串中所有单词被一个空格划分
- 模式串必须匹配字符串至少长度为1的单词
思路:
先把字符串根据空格划分。
接着我采用双字典的方式,分别记录最后出现的下标,详见代码吧,很好理解的
1 | class Solution(object): |