87. Scramble String
阿新 • • 發佈:2018-04-11
net != tails href eat leetcode esc recursive RM
87. 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.
解析
- 【LeetCode】87. Scramble String解法及註釋
題意在於判斷一個字符串是否為另一個字符串“亂序”得到,這種亂序采用的方式是將一個字符串從某個位置“割開”,形成兩個子串,然後對兩個子串進行同樣的“割開”操作,直到到達葉子節點,無法再分割。然後對非葉子節點的左右孩子節點進行交換,最後重新從左至右組合形成新的字符串,由於這個過程中存在字符位置的變化,因此,原來的字符串順序可能會被打亂,當然也可能沒有(同一個非葉子節點的左右孩子交換0次或偶數次,就無變化)。需要註意的點:
1、原字符串每次被割開的位置並不確定可能為[1,s.size()-1],所以必然需要遍歷所有可能割開的位置; 2、原字符串從第i個位置被割開(i在區間[1,s.size()-1]),形成的兩個子串s.substr(0,i)和s.substr(i,s.size()-i),如果這兩個子串不全為空,則它們的母串(這裏指原字符串)就是所謂的非葉子節點,這兩個子串可以左右交換(按照二叉樹的展開方式);對於兩個子串,可繼續割裂,直到形成葉子節點。
// 87. Scramble String
class Solution_87 {
public:
bool isScramble(string s1, string s2) {
if (s1==s2)
{
return true;
}
if (s1.size()!=s2.size())
{
return false;
}
vector<int> hash(26,0);
for (int i = 0; i < s1.size();i++)
{
hash[s1[i] - 'a' ]++;
hash[s2[i] - 'a']--;
}
for (int i = 0; i < 26;i++) //遞歸剪枝
{
if (hash[i]!=0)
{
return false;
}
}
bool res = false;
for (int i = 1; i < s1.size();i++) //遍歷所有可能割開的位置, 切割的長度
{
res = res || (isScramble(s1.substr(0, i), s2.substr(0, i)) && isScramble(s1.substr(i, s1.size() - i), s2.substr(i, s1.size() - i))); //長度要一致
res = res || (isScramble(s1.substr(0, i), s2.substr(s1.size() - i)) && isScramble(s1.substr(i),s2.substr(0, s1.size()-i)));
}
return res;
}
};
題目來源
- 87. Scramble String
87. Scramble String