题意:

image.png
image.png

解题思路:

  1. 思路:(递归)
  2. 1. 初始化判断两个字符长度是否相等,如果不等,则一定不能相互转化;
  3. 2. 循环遍历第一个字符串s1
  4. 2.1 如果没有翻转,则分别判断s1,s2 [s1, n-s1],[s2, n-s2]是否可以相互转化;
  5. 2.2 如果有翻转,则分别判断s1,s2的[s1, n-s2],[s2, n-s1]是否可以相互转化;

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param String $s1
  4. * @param String $s2
  5. * @return Boolean
  6. */
  7. function isScramble($s1, $s2) {
  8. if (strlen($s1) != strlen($s2)) return false;
  9. if ($s1 == $s2) return true;
  10. $str1 = $s1;
  11. $str2 = $s2;
  12. $strArr1 = str_split($str1);
  13. sort($strArr1);
  14. $str1 = implode('', $strArr1);
  15. $strArr2 = str_split($str2);
  16. sort($strArr2);
  17. $str2 = implode('', $strArr2);
  18. if ($str1 != $str2) return false;
  19. for ($i = 1; $i < strlen($s1); $i++) {
  20. // great => [g reat, r geat] => [gr eat, rg eat]
  21. if ($this->isScramble(substr($s1, 0, $i), substr($s2, 0, $i))
  22. && $this->isScramble(substr($s1, $i), substr($s2, $i))) {
  23. return true;
  24. }
  25. if ($this->isScramble(substr($s1, 0, $i), substr($s2, strlen($s2) - $i))
  26. && $this->isScramble(substr($s1, $i), substr($s2, 0, strlen($s2) - $i))) {
  27. return true;
  28. }
  29. }
  30. return false;
  31. }
  32. }

GO代码实现:

  1. func isScramble(s1 string, s2 string) bool {
  2. if s1 == s2 {
  3. return true
  4. }
  5. if len(s1)!=len(s2){
  6. return false
  7. }
  8. var s1Map, s2Map [26]int
  9. for i := 0; i < len(s1); i++ {
  10. s1Map[s1[i]-'a']++
  11. s2Map[s2[i]-'a']++
  12. }
  13. for i := 0; i < 26; i++ {
  14. if s1Map[i] != s2Map[i] {
  15. return false
  16. }
  17. }
  18. length := len(s1)
  19. for i := 1; i < len(s1); i++ {
  20. ls1, rs1 := s1[:i], s1[i:]
  21. ls2, rs2 := s2[:i], s2[i:]
  22. nb, mb := s2[length-i:], s2[:length-i]
  23. if isScramble(ls1, ls2) && isScramble(rs1, rs2) ||
  24. isScramble(ls1, nb) && isScramble(rs1, mb) {
  25. return true
  26. }
  27. }
  28. return false
  29. }