LeetCode-Scramble String
生活随笔
收集整理的這篇文章主要介紹了
LeetCode-Scramble String
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
哎,難題又不會做,
思路沒有什么難度,
關鍵是要把問題思考透徹,
要考慮的要點還是挺多的,不容易一下子都考慮到;
我開始的思路是按照樹的根去遞歸的,
這樣就必須要沒有重復元素,因為需要每次在s2中查找s1中的元素;
怎么說呢,有點考慮的過于specific了,其實直接把字符串分成兩部分遞歸就可以了,
不過需要注意不能漏掉兩部分可能次序調換的情況。
1 class Solution { 2 public: 3 bool isScramble(string s1, string s2) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 if (s1.empty() && s2.empty()) { 7 return true; 8 } 9 if (s1 == s2) { 10 return true; 11 } 12 return scramble(s1, 0, s1.size() - 1, s2, 0, s2.size() - 1); 13 } 14 bool scramble(string &s1, int b1, int e1, string &s2, int b2, int e2) { 15 if (!same(s1, b1, e1, s2, b2, e2)) { 16 return false; 17 } 18 int len = e1 - b1 + 1; 19 if (len == 0) { 20 return true; 21 } 22 if (len == 1) { 23 return (s1[b1] == s2[b2]); 24 } 25 for (int i = 0; i < len - 1; ++i) { 26 if ((scramble(s1, b1, b1 + i, s2, b2, b2 + i) && scramble(s1, b1 + i + 1, e1, s2, b2 + i + 1, e2)) || 27 (scramble(s1, b1, b1 + i, s2, e2 - i, e2)) && scramble(s1, b1 + i + 1, e1, s2, b2, e2 - i - 1)) { 28 return true; 29 } 30 } 31 return false; 32 } 33 bool same(string &s1, int b1, int e1, string &s2, int b2, int e2) { 34 vector<int> count(256, 0); 35 for (int i = b1; i <= e1; ++i) { 36 ++count[s1[i]]; 37 } 38 for (int i = b2; i <= e2; ++i) { 39 --count[s2[i]]; 40 } 41 for (int i = 0; i < 256; ++i) { 42 if (count[i] != 0) { 43 return false; 44 } 45 } 46 return true; 47 } 48 };?
轉載于:https://www.cnblogs.com/chasuner/p/scramble.html
總結
以上是生活随笔為你收集整理的LeetCode-Scramble String的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网站开发中JS中的常用语句
- 下一篇: 大漠插件最新版dm7.2135