-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
7cce0a0
commit 2c1961f
Showing
3 changed files
with
54 additions
and
6 deletions.
There are no files selected for viewing
This file contains 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
9 changes: 9 additions & 0 deletions
9
src/page-11/1071. Greatest Common Divisor of Strings/gcdOfStrings.spec.ts
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
import { gcdOfStrings } from './gcdOfStrings'; | ||
|
||
describe('1071. Greatest Common Divisor of Strings', () => { | ||
it('gcdOfStrings', () => { | ||
expect(gcdOfStrings('ABCABC', 'ABC')).toBe('ABC'); | ||
expect(gcdOfStrings('ABABAB', 'ABAB')).toBe('AB'); | ||
expect(gcdOfStrings('LEET', 'CODE')).toBe(''); | ||
}); | ||
}); |
29 changes: 29 additions & 0 deletions
29
src/page-11/1071. Greatest Common Divisor of Strings/gcdOfStrings.ts
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
type GcdOfStrings = (str1: string, str2: string) => string; | ||
|
||
export const gcdOfStrings: GcdOfStrings = (str1, str2) => { | ||
// Function to find GCD of two numbers | ||
function gcd(a: number, b: number): number { | ||
if (b === 0) return a; | ||
return gcd(b, a % b); | ||
} | ||
|
||
// Function to check if str can divide baseStr | ||
function divides(baseStr: string, str: string): boolean { | ||
if (baseStr.length % str.length !== 0) return false; | ||
const repeatedStr = str.repeat(baseStr.length / str.length); | ||
return repeatedStr === baseStr; | ||
} | ||
|
||
// Get the GCD of the lengths of the two strings | ||
const lenGCD = gcd(str1.length, str2.length); | ||
|
||
// Get the candidate GCD string | ||
const candidate = str1.substring(0, lenGCD); | ||
|
||
// Check if the candidate can divide both strings | ||
if (divides(str1, candidate) && divides(str2, candidate)) { | ||
return candidate; | ||
} | ||
|
||
return ''; | ||
}; |