Last active
September 28, 2025 20:38
-
-
Save mfaani/901d7abd5ab3206c8c0d07f421e11a41 to your computer and use it in GitHub Desktop.
#leetcode #array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
func gcdOfStrings(_ str1: String, _ str2: String) -> String { | |
if str2.count > str1.count { | |
return findGCDOf(str1: str2, str2: str1) | |
} else { | |
return findGCDOf(str1: str2, str2: str1) | |
} | |
} | |
func findGCDOf(str1: String, str2: String) -> String { | |
// - WHY: Reversing the indexes so we go from big range to small. Otherwise we may find a smaller common devisor and return early. | |
// - NOTE: `indices` doesn't return the `endIndex`. It only returns _valid_ indexes. So that's awesome. | |
for i in str2.indices.reversed() { | |
let subString = String(str2[str1.startIndex...i]) | |
if str1.isDivisible(byRepeating: subString) && str2.isDivisible(byRepeating: subString) { | |
return subString | |
} | |
} | |
return "" | |
} | |
} | |
extension String { | |
func isDivisible(byRepeating str: String) -> Bool { | |
var result = str | |
while self.count > result.count { | |
result += str | |
} | |
return result == self | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment