我在编码挑战中被问到了这个问题,但是我的解决方案通过了8/14个测试用例,但无法100%解决。我需要了解问题背后的逻辑。我的方法是找出串联t 0或n次是否可以得到s。如果是这样,我返回t的最长重复子串。
Given string s and string t, find the length of the smallest string x such that if x is concatenated any number of times, we get both s and t. If this is not possible return -1;
Example 1:
s = bcdbcdbcd
t = bcdbcd
If String t is concatenated twice, the result bcdbcdbcdbcd > s so s is not divisible by t. Return -1
Example 2:
s = bcdbcdbcdbcd
t = bcdbcd
If String t is concatenated twice, the result bcdbcdbcdbcd = s, so s is divisible by t. The smallest string x that can be concatenated to get both s and t is bcd. Return It’s length 3.
Example 3:
s = lrbb
t = lrbb
If String “lrbb” is concatenated once, we get string s and string t. Return It’s length 4
Example 4:
s = rbrb
t = rbrb
If String “rb” is concatenated twice, we get string s and string t. Return It’s length 2
如问题所述,x不必等于t。尝试使用s的最短重复子串,看看是否将t除。