-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathscramble_String.cpp
More file actions
75 lines (61 loc) · 1.71 KB
/
scramble_String.cpp
File metadata and controls
75 lines (61 loc) · 1.71 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
#include <bits/stdc++.h>
using namespace std;
bool isScramble(string S1, string S2)
{
// Strings of non-equal length
// cant' be scramble strings
if (S1.length() != S2.length()) {
return false;
}
int n = S1.length();
// Empty strings are scramble strings
if (n == 0) {
return true;
}
// Equal strings are scramble strings
if (S1 == S2) {
return true;
}
// Check for the condition of anagram
string copy_S1 = S1, copy_S2 = S2;
sort(copy_S1.begin(), copy_S1.end());
sort(copy_S2.begin(), copy_S2.end());
if (copy_S1 != copy_S2) {
return false;
}
for (int i = 1; i < n; i++) {
// Check if S2[0...i] is a scrambled
// string of S1[0...i] and if S2[i+1...n]
// is a scrambled string of S1[i+1...n]
if (isScramble(S1.substr(0, i), S2.substr(0, i))
&& isScramble(S1.substr(i, n - i),
S2.substr(i, n - i))) {
return true;
}
// Check if S2[0...i] is a scrambled
// string of S1[n-i...n] and S2[i+1...n]
// is a scramble string of S1[0...n-i-1]
if (isScramble(S1.substr(0, i),
S2.substr(n - i, i))
&& isScramble(S1.substr(i, n - i),
S2.substr(0, n - i))) {
return true;
}
}
// If none of the above
// conditions are satisfied
return false;
}
// Driver Code
int main()
{
string S1 = "coder";
string S2 = "ocred";
if (isScramble(S1, S2)) {
cout << "Yes";
}
else {
cout << "No";
}
return 0;
}