• 字符串的最大公因子


    此博客链接:https://www.cnblogs.com/ping2yingshi/p/12644155.html

    字符串的最大公因子(84min)

    题目链接:https://leetcode-cn.com/problems/greatest-common-divisor-of-strings/

    对于字符串 S 和 T,只有在 S = T + ... + T(T 与自身连接 1 次或多次)时,我们才认定 “T 能除尽 S”。

    返回最长字符串 X,要求满足 X 能除尽 str1 且 X 能除尽 str2。

    示例 1:

    输入:str1 = "ABCABC", str2 = "ABC"
    输出:"ABC"
    示例 2:

    输入:str1 = "ABABAB", str2 = "ABAB"
    输出:"AB"
    示例 3:

    输入:str1 = "LEET", str2 = "CODE"
    输出:""
     

    提示:

    1 <= str1.length <= 1000
    1 <= str2.length <= 1000
    str1[i] 和 str2[i] 为大写英文字母

    题解:

             方法:有最大公约数的字符串str1str2=str2+str1。

             说明:最大公约数的字符串X,str1是由n个X复制得来,str2也是由m个X复制得来,那str1+str2就是m+n个X复制得来的,而str2+str1也是由n+m个X复制来的,而当两个字符串不是由最大公约数X复制来                           时,str1+str2  和str2+str1是不相同的。例如:ABABAB和AB前面加后面和后面加前面都是ABABABAB,而ABCDEF和AB,前面加后面等于ABCDEFAB,后面加前面等于ABABCDEF两者是不相同的。

             思路:

                        1.先判断str1+str2和str2+str1是不是相同的。

                         2.求str1和str2的最大公约数。

                         3.从0遍历到最大公约数,每次遍历把字符加入到str中。

    心酸历程:

                    1.一开始想着遍历短的字符串长度,只要两个字符串的每个字符相等就重新加入str中,但是运行时ABABAB和ABAB的最大公约数是AB不是ABAB。

                     2.想到了利用求最大公约数,遍历到最大公约数长度,比较两个字符串的字符,但是这样少考虑的两个字符串只有最大公约数前面字母相等的情况。例如ABCDEF和ABCD。

                     3.先把求最大公约数的函数写好,发现不会用。

                      4.查看别人写的题解,看的是云里雾里。最后还是看了甜甜姐的看会了。

    代码入下:

    class Solution {
        public String gcdOfStrings(String str1, String str2) {
           int len1=str1.length();
           int len2=str2.length();
           String str="";
           if((str1+str2).equals(str2+str1))
           {
           for(int i=0;i<gac(len1,len2);i++)
           {
             
                     str+=str2.charAt(i);
           }
           return str;
           }
           else 
           return "";
        }
        public int gac(int len1,int len2)
        {
            int temp;
            while(len1%len2!=0)
            {
                temp=len1%len2;
                len1=len2;
                len2=temp;
            }
            return len2;
        }
    }
  • 相关阅读:
    pipelinewise 学习二 创建一个简单的pipeline
    pipelinewise 学习一 docker方式安装
    Supercharging your ETL with Airflow and Singer
    ubuntu中使用 alien安装rpm包
    PipelineWise illustrates the power of Singer
    pipelinewise 基于singer 指南的的数据pipeline 工具
    关于singer elt 的几篇很不错的文章
    npkill 一个方便的npm 包清理工具
    kuma docker-compose 环境试用
    kuma 学习四 策略
  • 原文地址:https://www.cnblogs.com/ping2yingshi/p/12644155.html
Copyright © 2020-2023  润新知