【Leetcode&C++】1071. Greatest Common Divisor of Strings

10 篇文章 0 订阅

问题描述

For two strings s and t , we say "t divides s " if and only if s = t + ... + t (i.e., t is concatenated with itself one or more times).
Given two strings str1 and str2 , return the largest string x such that x divides both str1 and str2 .

对于字符串s和t,当s=t+...+t(例如,t与自身连接一次或多次)时,可以说"t划分s"。

已知字符串str1和str2,返回可以划分str1和str2的最长字符串x。

举例

Example 1:
Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"
Example 2:
Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"
Example 3:
Input: str1 = "LEET", str2 = "CODE"
Output: ""
str1="MJBUJMJBUJMJBUJMJBUJMJBUJMJBUJMJBUJMJBUJ"
str2="MJBUJMJBUJMJBUJMJBUJMJBUJMJBUJMJBUJMJBUJMJBUJMJBUJMJBUJMJBUJMJBUJMJBUJMJBUJMJBUJMJBUJ"
expected: MJBUJ

str1="ABABABAB"
str2="ABAB"
expected: ABAB

解决方法

#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

class Solution {
public:
    string gcdOfStrings(string str1, string str2) {
        return (str1 + str2 == str2 + str1)? str1.substr(0, __gcd(size(str1),size(str2))): "";
    }
};

首先判断两个字符串相加后是否相等。

str1="ABCCAB", str2="AB"
str1 + str2 = "ABCCABAB"
str2 + str1 = "ABABCCAB"
∴不存在同时划分str1和str2的字符串
str1="ABAB", str2="AB"
str1 + str2 = "ABABAB"
str2 + str1 = "ABABAB"
∴存在同时划分str1和str2的字符串

如果存在,利用c++的gcd方法得到两个字符串长度的最大公约数,返回前最大公约数的字符串。

s=t+...+t,要意识到size(s) % size(t) = 0, 即s的长度可以被t的长度整除。由最长字符串联想到最大公约数。

最大公约数(Greatest common divisor)

由于直接调用gcd方法有些无聊。尝试写一下返回最大公约数的函数。

//递归写法
int my_gcd2(int a, int b, int divisor)
{
    if(a % divisor == 0 && b % divisor == 0)
        return divisor;
    
    return my_gcd2(a, b, divisor-1);
}
int my_gcd(int a, int b)
{
    int divisor = (a < b)? a: b;
    return my_gcd2(a, b, divisor);
} 

更精简的代码,出自这里

int gcd(int n, int m) {
   for (int i = m <= n ? m : n; i > 1; i--) { //顺带复习:<=的运算顺序是自右向左的
       if (n % i == 0 && m % i == 0) return i;
   }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值