sudopower

lc_1701

LC: 1071: Common Divisor of String

Link to problem

Solution 1

func gcdOfStrings(str1 string, str2 string) string {
    // in a loop check if they're equal upto min length else return empty
    // loop over shortest string and build prefix in each run
    // in an inner loop check if prefix holds up, if it does not break and continue building prefix
    // save prefix if loop completes, clear it when breaking out of inner loop

    // above logic does not work, gotta know GCD and euclids formula
    // to be repeating by x combination of str1 and str2 should be equal else return empty
    // return the string from 0 to GCD or lengths pf both strings

    if str1+str2!=str2+str1{
        return ""
    }

    return str1[:GCD(len(str1),len(str2))]
}

func GCD(a, b int) int {
	for b != 0 {
		t := b
		b = a % b
		a = t
	}
	return a
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Blogs