GCD string

topic

For strings S and T, only S = T + ... + time T (T connected to itself one or more times), we identified "T S can be divisible." Returns the longest string X, X can meet the requirements, and X can be divisible divisible str1 str2.
Topic link: https: //leetcode-cn.com/problems/greatest-common-divisor-of-strings

Problem-solving ideas

If a string of length 1 0, the process directly returns ""
2. determine whether the two are equal, it can not be divided not satisfied, return ""
3. Get the greatest common divisor, Euclidean algorithm
4. interception string

Code

class Solution {   
 public String gcdOfStrings(String str1, String str2) {      
   if(str1.length()==0 || str2.length()==0) //若有一个字符串长度为0,则直接返回""     
      return "";        
      //判断两者是否相等,若不满足则不能除尽     
  if(!(str1+str2).equals(str2+str1))
      return "";       
      int x=gcd(str1.length(),str2.length());//获取最大公约数         
      return str1.substring(0,x);//截取字符串   
   }   
           //欧几里德算法    
 public int gcd(int a,int b){    
         return b==0?a:gcd(b,a%b);   
    }
  }
Published 38 original articles · won praise 0 · Views 1134

Guess you like

Origin blog.csdn.net/weixin_45489155/article/details/104817289
gcd