[Array] 1071. Greatest common factor of strings

1071. Greatest Common Factor of Strings

problem solving ideas

  • Roll and divide
  • Calculates the greatest common factor of the lengths of two strings
  • Then intercept the string length
  • Before using the rolling and dividing method, it is necessary to judge whether there is a greatest common factor
class Solution {
    
    
    private int al(int length1, int length2){
    
    
        if(length2 == 0){
    
    
            return length1;
        }else{
    
    
            // 说明余数不为0
            // 使用当前余数除以 当前除数
            return al(length2,length1 % length2);
        }
    }

    public String gcdOfStrings(String str1, String str2) {
    
    
        // 求两个字符串的最大公因子  
        // 辗转相除法
        // 首先验证是否存在最大公约数
        if(!(str1 + str2).equals(str2 + str1)){
    
    
            return "";// 不存在 返回空串
        }

        // 求出两个字符串长度的最大公因子  然后截取字符串
        return str1.substring(0,al(str1.length(),str2.length()));
    }
}

Guess you like

Origin blog.csdn.net/qq_44653420/article/details/131763364