• LeetCode "Scramble String"


    I have to admit that I'm still an algorithm rookie: in front of a problem, I got lost on what the nature of the problem is.. usually I made everything too complex unnecessarily. 

    As the graph on the page shows, it is recursive model. So DFS with pruning is a good choice: http://zhaohongze.com/wordpress/2013/12/12/leetcode-scramble-string/

    My code:

    class Solution {
    public:
        bool hasSameLetters(string s1, string s2)
        {
            std::sort(s1.begin(), s1.end());
            std::sort(s2.begin(), s2.end());
            return s1.compare(s2) == 0;
        }
        bool isScramble(string s1, string s2) {
            size_t len1 = s1.length();
            size_t len2 = s2.length();
            if (len1 != len2) return false;
    
            //    Base case: len 1 and 2
            if (len1 == 1)
                return s1 == s2;
            else if (len1 == 2)
                return (s1[0] == s2[0] && s1[1] == s2[1]) || (s1[0] == s2[1] && s1[1] == s2[0]);
    
            if (s1.compare(s2) == 0) return true;
            //
            for (int k = 1; k < len1; k++)
            {
                string s11 = s1.substr(0, k);
                string s12 = s1.substr(k, len1 - k);
                string s21 = s2.substr(0, k);
                string s22 = s2.substr(k, len1 - k);
    
                if (hasSameLetters(s11, s21) && hasSameLetters(s12, s22))                
                    if (isScramble(s11, s21) && isScramble(s12, s22))
                        return true;
    
                if (hasSameLetters(s11, s22) && hasSameLetters(s12, s21))
                    if (isScramble(s11, s22) && isScramble(s12, s21))
                        return true;
    
                s21 = s2.substr(0, len2 - k);
                s22 = s2.substr(len2 - k, k);
    
                if (hasSameLetters(s11, s21) && hasSameLetters(s12, s22))
                    if (isScramble(s11, s21) && isScramble(s12, s22))
                        return true;
    
                if (hasSameLetters(s11, s22) && hasSameLetters(s12, s21))
                    if (isScramble(s11, s22) && isScramble(s12, s21))
                        return true;
            }
    
            return false;
        }
    };
  • 相关阅读:
    [USACO09Open] Tower of Hay 干草塔
    [HNOI2004]打鼹鼠
    BZOJ1222[HNOI 2001]产品加工
    BZOJ1270[BJWC2008]雷涛的小猫
    NOIP2018出征策
    解析·NOIP·冷门 CLZ最小环
    CCF-NOIP-2018 提高组(复赛) 模拟试题(九)(2018 CSYZ长沙一中)
    [脚本无敌1]图片批量处理(matlab)
    用Matlab解《2013年数据建模比赛》图像碎片拼接题
    火灾检测-fire,fire
  • 原文地址:https://www.cnblogs.com/tonix/p/3932458.html
Copyright © 2020-2023  润新知