[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 };

 

目录
相关文章
|
5月前
|
算法 C++
【LeetCode】【C++】string OJ必刷题
【LeetCode】【C++】string OJ必刷题
32 0
|
6天前
|
存储 编译器 Linux
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
|
6月前
|
Java
Leetcode 467. Unique Substrings in Wraparound String
大概翻译下题意,有个无限长的字符串s,是由无数个「abcdefghijklmnopqrstuvwxy」组成的。现在给你一个字符串p,求多少个p的非重复子串在s中出现了?
24 0
|
存储 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.
65 0
LeetCode 438. Find All Anagrams in a String
|
存储
LeetCode 394. Decode String
给定一个经过编码的字符串,返回它解码后的字符串。 编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。 你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。 此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
63 0
LeetCode 394. Decode String
|
索引
LeetCode 345. Reverse Vowels of a String
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
54 0
LeetCode 345. Reverse Vowels of a String
|
6天前
|
算法 C++
【刷题】Leetcode 1609.奇偶树
这道题是我目前做过最难的题,虽然没有一遍做出来,但是参考大佬的代码,慢慢啃的感觉的真的很好。刷题继续!!!!!!
9 0