1146. Greatest Common Divisor of Strings
My accepted C++ solution to LeetCode problem 1146, Greatest Common Divisor of Strings, running in 0ms.
- Difficulty: Easy
- C++
- Runtime 0ms
- Memory 9.7MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
C++
Accepted on LeetCode — runtime 0ms, memory 9.7MB, accepted 2025-12-28.
class Solution {
public:
string gcdOfStrings(string str1, string str2) {
// If there's a common divisor, str1 + str2 == str2 + str1
if (str1 + str2 != str2 + str1) return "";
// The GCD of lengths gives us the length of the result
return str1.substr(0, __gcd((int)str1.size(), (int)str2.size()));
}
};