Leetcode 87. Scramble String
2016-06-13 21:57
399 查看
问题
https://leetcode.com/problems/scramble-string/解法1
递归时间复杂度O(n^n)?
class Solution { public: bool isScramble(string s1, string s2) { if (s1.size() != s2.size()) return false; if (s1.size() ==1) return s1==s2; int num[256]={0}; for (int i=0; i<s1.size(); ++i) { ++num[s1[i]]; --num[s2[i]]; } for (int i=0; i< 256; ++i) if (num[i]) return false; for (int i=1; i<s1.size(); ++i) { if (isScramble(s1.substr(0, i), s2.substr(0, i)) && isScramble(s1.substr(i), s2.substr(i)) || isScramble(s1.substr(0, i), s2.substr(s1.size() -i)) && isScramble(s1.substr(i), s2.substr(0, s1.size()-i))) return true; } return false; } };
解法二
dp 时间复杂度(n^4) 空间复杂度(n^3)class Solution { public: bool isScramble(string s1, string s2) { if (s1.size() != s2.size()) return false; int n = s1.size(); if (n==0) return true; if (n==1) return s1 == s2; bool dp[n+1] ; memset(dp, 0, sizeof(dp)); for (int x =0; x< n; ++x) for (int y=0; y<n; ++y) if (s1[x] == s2[y]) dp[1][x][y] = true; for (int len = 2; len <=n; ++len) for (int x=0; x+len <=n; ++x) for (int y =0; y+len<=n; ++y) for (int len1=1; len1<len; ++len1) { int len2 = len -len1; if (dp[len1][x][y] && dp[len2][x+len1][y+len1] || dp[len1][x][y+len2] && dp[len2][x+len1][y]) dp[len][x][y] = true; } return dp [0][0]; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解