Word Pattern II
Given apattern
and a stringstr
, find ifstr
follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter inpattern
and a non-empty substring instr
.(i.e ifa
corresponds tos
, thenb
cannot correspond tos
. For example, given pattern ="ab"
, str ="ss"
, returnfalse
.)
Notice:
You may assume bothpattern
andstr
contains only lowercase letters.
Example
Given pattern ="abab"
, str ="redblueredblue"
, returntrue
.
Given pattern ="aaaa"
, str ="asdasdasdasd"
, returntrue
.
Given pattern ="aabb"
, str ="xyzabcxzyabc"
, returnfalse
.
Note
类似Word Pattern,不过这里没有给你分词了,需要自己暴力去试,依旧需要双向mapping(Map + Set)
逻辑:
如果map包含字符,看看当前substring是不是以这个map的value开头,不是就false了,递归传递子串
如果map不包含字符,暴力一个个位置拆分去试,for循环,如果set里面有,则continue继续找(必须双向映射)
Time:O(2^len_str) (因为隐含条件是 len_pattern <= len_str)
Space: O(2^len_str * wordLength)
Code
Last updated