https://leetcode.com/problems/greatest-common-divisor-of-strings/
For strings S and T, we say "T divides S" if and only if S = T + ... + T (T concatenated with itself 1 or more times)
Return the largest string X such that X divides str1 and X divides str2.
Example 1: Input: str1 = "ABCABC", str2 = "ABC" Output: "ABC" Example 2: Input: str1 = "ABABAB", str2 = "ABAB" Output: "AB" Example 3: Input: str1 = "LEET", str2 = "CODE" Output: "" Note: 1 <= str1.length <= 1000 1 <= str2.length <= 1000 str1[i] and str2[i] are English uppercase letters.
I had 30 minutes to solve this. please review this as a real interview.
what is a red flag, remember code will not be prefect.
using System;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace StringQuestions
{
/// <summary>
/// https://leetcode.com/problems/greatest-common-divisor-of-strings/
/// </summary>
[TestClass]
public class GreatestCommonDivisorOfStringsTest
{
[TestMethod]
public void TestMethod1()
{
string str1 = "ABABAB";
string str2 = "ABAB";
string res = GCDOfStringsclass.GcdOfStrings(str1, str2);
Assert.AreEqual("AB", res);
}
[TestMethod]
public void TestMethod2()
{
string str1 = "ABCDEF";
string str2 = "ABC";
string res = GCDOfStringsclass.GcdOfStrings(str1, str2);
Assert.AreEqual(string.Empty, res);
}
}
public class GCDOfStringsclass
{
public static string GcdOfStrings(string str1, string str2)
{
int min = Math.Min(str1.Length, str2.Length);
StringBuilder build = new StringBuilder();
//build largest prefix
for (int i = 0; i < min; i++)
{
if (str1[i] != str2[i])
{
break;
}
build.Append(str1[i]);
}
// no common prefix
string prefix = build.ToString();
if (prefix.Length == 0)
{
return string.Empty;
}
while (str1.Length % prefix.Length != 0 || str2.Length % prefix.Length != 0)
{
prefix = prefix.Remove(prefix.Length - 1);
if (prefix.Length == 0)
{
return string.Empty;
}
}
for (int i = 0; i < str1.Length / prefix.Length; i++)
{
for (int j = 0; j < prefix.Length; j++)
{
if (str1[j + prefix.Length * i] != prefix[j])
{
return string.Empty;
}
}
}
for (int i = 0; i < str2.Length / prefix.Length; i++)
{
for (int j = 0; j < prefix.Length; j++)
{
if (str2[j + prefix.Length * i] != prefix[j])
{
return string.Empty;
}
}
}
return prefix;
}
}
}