2023-03-30 Daily Challenge
Today I have done leetcode's March LeetCoding Challenge with cpp
.
March LeetCoding Challenge 30
Description
Scramble String
We can scramble a string s to get a string t using the following algorithm:
- If the length of the string is 1, stop.
- If the length of the string is > 1, do the following:
- Split the string into two non-empty substrings at a random index, i.e., if the string is
s
, divide it tox
andy
wheres = x + y
. - Randomly decide to swap the two substrings or to keep them in the same order. i.e., after this step,
s
may becomes = x + y
ors = y + x
. - Apply step 1 recursively on each of the two substrings
x
andy
.
- Split the string into two non-empty substrings at a random index, i.e., if the string is
Given two strings s1
and s2
of the same length, return true
if s2
is a scrambled string of s1
, otherwise, return false
.
Example 1:
Input: s1 = "great", s2 = "rgeat" Output: true Explanation: One possible scenario applied on s1 is: "great" --> "gr/eat" // divide at random index. "gr/eat" --> "gr/eat" // random decision is not to swap the two substrings and keep them in order. "gr/eat" --> "g/r / e/at" // apply the same algorithm recursively on both substrings. divide at random index each of them. "g/r / e/at" --> "r/g / e/at" // random decision was to swap the first substring and to keep the second substring in the same order. "r/g / e/at" --> "r/g / e/ a/t" // again apply the algorithm recursively, divide "at" to "a/t". "r/g / e/ a/t" --> "r/g / e/ a/t" // random decision is to keep both substrings in the same order. The algorithm stops now, and the result string is "rgeat" which is s2. As one possible scenario led s1 to be scrambled to s2, we return true.
Example 2:
Input: s1 = "abcde", s2 = "caebd" Output: false
Example 3:
Input: s1 = "a", s2 = "a" Output: true
Constraints:
s1.length == s2.length
1 <= s1.length <= 30
s1
ands2
consist of lowercase English letters.
Solution
auto speedup = [](){
cin.tie(nullptr);
cout.tie(nullptr);
ios::sync_with_stdio(false);
return 0;
}();
class Solution {
unordered_map<string, bool> result;
public:
bool isScramble(string s1, string s2) {
if(s1 == s2) return true;
int len = s1.length();
if(result.count(s1 + s2)) return result[s1 + s2];
vector<int> a(26), b(26), c(26);
for(int i = 1; i < len; ++i) {
int j = len - i;
a[s1[i - 1] - 'a'] += 1;
b[s2[i - 1] - 'a'] += 1;
c[s2[j] - 'a'] += 1;
if(a == b && isScramble(s1.substr(0, i), s2.substr(0, i)) && isScramble(s1.substr(i), s2.substr(i))) {
result[s1 + s2] = true;
return true;
}
if(a == c && isScramble(s1.substr(0, i), s2.substr(j)) && isScramble(s1.substr(i), s2.substr(0, j))) {
result[s1 + s2] = true;
return true;
}
}
result[s1 + s2] = false;
return false;
}
};
// Accepted
// 288/288 cases passed (3 ms)
// Your runtime beats 99.15 % of cpp submissions
// Your memory usage beats 79.89 % of cpp submissions (15.2 MB)