LeetCode: Scramble String
Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.
Below is one possible representation of s1 = "great"
:
great
/ \
gr eat
/ \ / \
g r e at
/ \
a t
To scramble the string, we may choose any non-leaf node and swap its two children.
For example, if we choose the node "gr"
and swap its two children, it produces a scrambled string "rgeat"
.
rgeat
/ \
rg eat
/ \ / \
r g e at
/ \
a t
We say that "rgeat"
is a scrambled string of "great"
.
Similarly, if we continue to swap the children of nodes "eat"
and "at"
, it produces a scrambled string "rgtae"
.
rgtae
/ \
rg tae
/ \ / \
r g ta e
/ \
t a
We say that "rgtae"
is a scrambled string of "great"
.
Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1.
地址:https://oj.leetcode.com/problems/scramble-string/
算法:如果字串S1[0~i]和S2[0~i]以及S1[i+1~n]和S2[i+1~n]都满足scrambled条件,那么S1和S2也满足;如果字串S1[0~i]和S2[n-i~n]以及S1[i+1~n]和S2[0~n-i-1]满足scrambled条件,那么S1和S2也满足,其中i=1...n。注意,我们在递归调用之前,用函数isReasonString先判断一下是否有可能满足scrambled条件,这样可以减少递归的次数。代码:
1 class Solution {
2 public:
3 bool isScramble(string s1, string s2) {
4 if(s1 == s2){
5 return true;
6 }
7 if(s1.size() == 1){
8 return false;
9 }
10 int len = s1.size();
11 for(int i = 1; i < len; ++i){
12 string s11 = s1.substr(0,i);
13 string s21 = s2.substr(0,i);
14 string s12 = s1.substr(i,len-i);
15 string s22 = s2.substr(i,len-i);
16 if(isReasonString(s11,s21) && isReasonString(s12,s22) && isScramble(s11,s21) && isScramble(s12,s22)){
17 return true;
18 }
19 s21 = s2.substr(len-i,i);
20 s22 = s2.substr(0,len-i);
21 if(isReasonString(s11,s21) && isReasonString(s12,s22) && isScramble(s11,s21) && isScramble(s12,s22)){
22 return true;
23 }
24 }
25 return false;
26 }
27 bool isReasonString(string s1, string s2){
28 sort(s1.begin(),s1.end());
29 sort(s2.begin(),s2.end());
30 return s1 == s2;
31 }
32 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合终身会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一则复杂 SQL 改写后有感
· golang中写个字符串遍历谁不会?且看我如何提升 50 倍
· C# 代码如何影响 CPU 缓存速度?
· 智能桌面机器人:使用 .NET 为树莓派开发 Wifi 配网功能
· C# 模式匹配全解:原理、用法与易错点
· 一则复杂 SQL 改写后有感
· 曾经风光无限的 Oracle DBA 已经落伍了吗?
· 接口被刷百万QPS,怎么防?
· C# 锁机制全景与高效实践:从 Monitor 到 .NET 9 全新 Lock
· 一个开源免费、功能丰富的 WPF 自定义控件资源库