zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    hdu-1862 EXCEL排序
    hdu-1754 I Hate It
    hdu-1538 A Puzzle for Pirates
    在Window下安装Linux (ubuntu-16.04.2)
    Python爬虫--简单的单词查询
    Linux下MySQL在知道密码的情况下修改密码
    Linux下忘记MySQL密码的解决方法和输入mysqld_safe --skip-grant-tables &后无法进入MySQL的解决方法
    Python的下载及安装
    在Netbeans的项目中添加JDBC驱动程序
    Mac下截屏方法
  • 原文地址:https://www.cnblogs.com/tonix/p/3932458.html
Copyright © 2011-2022 走看看