-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path291.txt
More file actions
90 lines (66 loc) · 2.36 KB
/
291.txt
File metadata and controls
90 lines (66 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
Given a pattern and a string s, return true if s matches the pattern.
A string s matches a pattern if there is some bijective mapping of single characters to strings such that if each character in pattern is replaced by the string it maps to, then the resulting string is s. A bijective mapping means that no two characters map to the same string, and no character maps to two different strings.
Example 1:
Input: pattern = "abab", s = "redblueredblue"
Output: true
Explanation: One possible mapping is as follows:
'a' -> "red"
'b' -> "blue"
Example 2:
Input: pattern = "aaaa", s = "asdasdasdasd"
Output: true
Explanation: One possible mapping is as follows:
'a' -> "asd"
Example 3:
Input: pattern = "abab", s = "asdasdasdasd"
Output: true
Explanation: One possible mapping is as follows:
'a' -> "a"
'b' -> "sdasd"
Note that 'a' and 'b' cannot both map to "asd" since the mapping is a bijection.
Example 4:
Input: pattern = "aabb", s = "xyzabcxzyabc"
Output: false
Constraints:
0 <= pattern.length <= 20
0 <= s.length <= 50
pattern and s consist of only lower-case English letters.
class Solution {
String t[]=new String[26];
boolean res=false;
public boolean wordPatternMatch(String pattern, String s) {
for(int i=0;i<t.length;i++){
t[i]="";
}
dfs(pattern,s,0,0,new HashSet<>());
return res;
}
public void dfs(String pattern, String s,int pindex,int sindex,Set<String>set){
if(pindex>=pattern.length()){
if(sindex>=s.length()){
res=true;
}
return;
}
if(sindex>=s.length())return;
char c=pattern.charAt(pindex);
if(t[c-'a'].length()!=0){
String mat=t[c-'a'];
if(sindex+mat.length()-1>=s.length()||!(s.substring(sindex,sindex+mat.length()).equals(mat)))return;
dfs(pattern,s,pindex+1,sindex+mat.length(),set);
}
else{
StringBuilder str=new StringBuilder();
for(int i=sindex;i<s.length();i++){
str.append(s.charAt(i));
String ss=str.toString();
if(set.contains(ss))continue;
set.add(ss);
t[c-'a']=ss;
dfs(pattern,s,pindex+1,i+1,set);
t[c-'a']="";
set.remove(ss);
}
}
}
}