1071. Greatest Common Divisor of Strings/智力題

題目描述

For strings S and T, we say "T divides S" if and only if S = T + ... + T  (T concatenated with itself 1 or more times)

Return the largest string X such that X divides str1 and X divides str2.

 

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: ""

 

Note:

  1. 1 <= str1.length <= 1000
  2. 1 <= str2.length <= 1000
  3. str1[i] and str2[i] are English uppercase letters.

解析

如果它們有公因子 abc,那麼 str1 就是 mmmabc 的重複,str2nnnabc 的重複,連起來就是 m+nm+nm+nabcm+nm+nm+nabcn+mn+mn+mabc 是一樣的。

可以想到 str1 + str2 !== str2 + str1 是無解的充要條件

如果有解,那麼最長公共子串就是s1.substr(0,gcd(s1.size(),s2.size())).
class Solution {
public:
    string gcdOfStrings(string str1, string str2) {
        if(str1+str2!=str2+str1) return "";
        return str1.substr(0,gcd(str1.size(),str2.size()));
    }
    int gcd(int a,int b){
        return b==0?a:gcd(b,a%b);
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章