[LeetCode] Scramble String

简介: To solve this problem, you first need to understand it well. The key problem is tell the difference of  scramble from permutations.

To solve this problem, you first need to understand it well. The key problem is tell the difference of  scramble from permutations. You may refer to this link for some nice discussions. Then you can proceed to solve it. This link posts a very easy and also very fast code, which is very readable. I almost copy it below.

 1 class Solution {
 2 public:
 3     bool isScramble(string s1, string s2) {
 4         if (s1 == s2) return true;
 5         int n = s1.length();
 6         int counts[26] = {0};
 7         for (int i = 0; i < n; i++) {
 8             counts[s1[i] - 'a']++;
 9             counts[s2[i] - 'a']--;
10         }
11         for (int i = 0; i < 26; i++)
12             if (counts[i]) return false;
13         for (int i = 1; i < n; i++) {
14             if (isScramble(s1.substr(0, i), s2.substr(0, i)) && isScramble(s1.substr(i), s2.substr(i)))
15                 return true;
16             if (isScramble(s1.substr(0, i), s2.substr(n - i)) && isScramble(s1.substr(i), s2.substr(0, n - i)))
17                 return true;
18         }
19         return false;
20     }
21 };

 

目录
相关文章
|
存储 canal 算法
leetcode:43. 字符串相乘(附加一些C++string其他小练习)
leetcode:43. 字符串相乘(附加一些C++string其他小练习)
|
算法 索引
【LeetCode】string 类的几道简单题
【LeetCode】string 类的几道简单题
【LeetCode】string 类的几道简单题
|
机器学习/深度学习 NoSQL 算法
LeetCode 344. 反转字符串 Reverse String
LeetCode 344. 反转字符串 Reverse String
LeetCode 438. Find All Anagrams in a String
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. The order of output does not matter.
264 0
LeetCode 438. Find All Anagrams in a String
|
存储
LeetCode 394. Decode String
给定一个经过编码的字符串,返回它解码后的字符串。 编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。 你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。 此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
307 0
LeetCode 394. Decode String
|
索引
LeetCode 345. Reverse Vowels of a String
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
250 0
LeetCode 345. Reverse Vowels of a String
|
机器学习/深度学习 NoSQL
LeetCode 344. Reverse String
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。 不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
245 0
LeetCode 344. Reverse String
|
索引
LeetCode 97. Interleaving String
给定s1,s2,s3,确定s3是否由s1和s2的交织形成,若是返回True,若不是则返回False.
264 0
LeetCode 97. Interleaving String
LeetCode 87. Scramble String
题意是给定两个字符串,判断他们是否满足某种关系.
237 0
LeetCode 87. Scramble String
Leetcode-Easy 806. Number of Lines To Write String
Leetcode-Easy 806. Number of Lines To Write String
205 0