---
# System prepended metadata

title: 1071. Greatest Common Divisor of Strings
tags: [Leetcode]

---

<style>
    html, body, .ui-content {
    background: #222222;
    color: #00BFFF;
}
    /* 設定 code 模板 */
    .markdown-body code,
.markdown-body tt {
    background-color: #ffffff36;
}
.markdown-body .highlight pre,
.markdown-body pre {
    color: #ddd;
    background-color: #00000036;
}
.hljs-tag {
    color: #ddd;
}
.token.operator {
  background-color: transparent;
}    
/* 設定連結 */
a,
.open-files-container li.selected a {
    color: #89FFF8;
    
}
a:hover,
.open-files-container li.selected a:hover {
    color: #89FFF890;
}
   
</style>

###### tags: `Leetcode`

# 1071. Greatest Common Divisor of Strings

###### Link : https://leetcode.com/problems/greatest-common-divisor-of-strings/description/

## 題目
回傳GCD of Strings
**GCD of Strings:
t divides s" if and only if s = t + ... + t**
## 程式碼
```cpp=
class Solution {
public:
    string gcdOfStrings(string str1, string str2) {
        string ans, temp;
        const int size1 = str1.size(), size2 = str2.size();
        for(int i = 0;i < size2;i++){
            temp += str2[i];
            if(isDivisor(str1, temp) && isDivisor(str2, temp) && temp.size() > ans.size())
                ans = temp;
        }
        return ans;
    }
    bool isDivisor(string &str, string &sub){
        const int strSize = str.size(), subSize = sub.size();
        if(strSize % subSize != 0) return false;
        int i =0, j = 0;
        while(i < strSize){
            if(str[i] != sub[j]) return false;
            ++i, ++j;
            if(j >= subSize) j = 0;
        }
        return true;
    }
};
```

## Date 
### 2023/2/1