LeetCode 笔记系列 19 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.
完全没有思路。
卡了很久,最后参考这里的解释。写了一个递归的版本解决。
代码:

public boolean isScramble(String s1, String s2) { // Start typing your Java solution below // DO NOT write main() function if(!isContainSameChars(s1, s2))return false; if(s1.equals(s2)) return true; for(int split = 1; split < s1.length(); split++){ String s11 = s1.substring(0, split); String s12 = s1.substring(split); String s21 = s2.substring(0, split); String s22 = s2.substring(split); if(isScramble(s11, s21) && isScramble(s12, s22)) return true; s21 = s2.substring(0, s2.length() - split); s22 = s2.substring(s2.length() - split); if(isScramble(s11, s22) && isScramble(s12, s21)) return true; } return false; }
其实不算难。除非你想不到递归。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步