291. Word Pattern II
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 substring in str
.
Examples:
- pattern =
"abab"
, str ="redblueredblue"
should return true. - pattern =
"aaaa"
, str ="asdasdasdasd"
should return true. - pattern =
"aabb"
, str ="xyzabcxzyabc"
should return false.
Notes:
You may assume both pattern
and str
contains only lowercase letters.
本题是一个比较hard的题目,需要使用回溯的方法来做,这里面创建两个hashtable,一个hashmap用来存储char-String对,另一个hashset用来检验是否存在重复的字符串;回溯法肯定要用递归的思路,传递的参数有两个hashtable,两个索引,还有pattern和str;首先判断终止条件,即如果两个索引都达到了两个字符串的长度值,则返回true,如果只有一个到达了,则返回false;然后找字符在索引处的值,如果map里面包含它,获取其值,看其是否在str中,这里面又个java api,叫做startsWith,可以用这个来解决。如果不在str里面,返回false;如果在的话,继续递归;如果不包含在map里面,则创建一个紧邻的子字符串,看hashset包含否,包含的话说明之前用过这个,没有通过,则扩大子字符串,如果不包含,则把它放进map,set里面,然后把剩下的遍历,如果遍历失败,则移除掉(整体来说回溯的思路)。代码如下:
1 public class Solution { 2 public boolean wordPatternMatch(String pattern, String str) { 3 Map<Character,String> map = new HashMap<Character,String>(); 4 Set<String> set = new HashSet<String>(); 5 return isMatch(pattern,0,str,0,map,set); 6 } 7 public boolean isMatch(String pat,int i,String str,int j,Map<Character,String> map,Set<String> set){ 8 if(i==pat.length()&&j==str.length()) return true; 9 if(i==pat.length()||j==str.length()) return false; 10 char c = pat.charAt(i); 11 if(map.containsKey(c)){ 12 String s = map.get(c); 13 if(!str.startsWith(s,j)){ 14 return false; 15 } 16 return isMatch(pat,i+1,str,j+s.length(),map,set); 17 } 18 for(int k=j;k<str.length();k++){ 19 String s = str.substring(j,k+1); 20 if(set.contains(s)){ 21 continue; 22 } 23 map.put(c,s); 24 set.add(s); 25 if(isMatch(pat,i+1,str,k+1,map,set)){ 26 return true; 27 } 28 map.remove(c); 29 set.remove(s); 30 } 31 return false; 32 } 33 }