forked from yuanx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScrambleString.java
More file actions
75 lines (61 loc) · 1.96 KB
/
ScrambleString.java
File metadata and controls
75 lines (61 loc) · 1.96 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
// Recursive solve the issue, exponential time, could not pass the larger judge
public class Solution {
public boolean isScramble(String s1, String s2) {
// Start typing your Java solution below
// DO NOT write main() function
int len = s1.length();
if(len != s2.length()) return false;
if(len == 1)
return (s1.charAt(0) == s2.charAt(0) ? true : false);
for(int i=1; i<len; i++){
if((isScramble(s1.substring(0,i), s2.substring(0,i)) && isScramble(s1.substring(i), s2.substring(i))) || (isScramble(s1.substring(len-i), s2.substring(0,i)) && isScramble(s1.substring(0,len-i), s2.substring(i))))
return true;
}
return false;
}
}
// Recursive solve with cache, pass both test
import java.util.Hashtable;
public class Solution {
public boolean isScramble(String s1, String s2) {
// Start typing your Java solution below
// DO NOT write main() function
Hashtable<String, Boolean> hash = new Hashtable<String, Boolean>();
return ifScramble(s1,s2, hash);
}
public boolean ifScramble(String s1, String s2, Hashtable<String, Boolean> hash){
String temp;
if(s1.compareTo(s2)>0)
temp = s1+s2;
else
temp = s2+s1;
boolean re = false;
if(hash.containsKey(temp))
return hash.get(temp);
else{
int len = s1.length();
if(len != s2.length()){
hash.put(temp, false);
return false;
}
if(len == 1){
re = (s1.charAt(0) == s2.charAt(0) ? true : false);
hash.put(temp, re);
return re;
}
if(s1.equals(s2)){
hash.put(temp, true);
return true;
}
for(int i=1; i<len; i++){
if((ifScramble(s1.substring(0,i), s2.substring(0,i), hash) && ifScramble(s1.substring(i), s2.substring(i), hash)) || (ifScramble(s1.substring(len-i), s2.substring(0,i), hash) && ifScramble(s1.substring(0,len-i), s2.substring(i), hash)))
{
hash.put(temp, true);
return true;
}
}
hash.put(temp, false);
return false;
}
}
}