检查Python字符串是否可重复构成另一字符串
假设我们有两个字符串s和t,我们需要找到字符串s可以连接多少次才能生成t。如果无法使用s生成t,则返回-1。
因此,如果输入类似于s = "tom" t = "tomtomtom",则输出将为3,因为我们可以将"tom"连接3次以获得"tomtomtom"。
为了解决这个问题,我们将遵循以下步骤:
- 如果t的长度不能被s的长度整除,则
- 返回-1
- cnt := (t的长度 / s的长度)的商
- s := 将s连接cnt次
- 如果s与t相同,则
- 返回cnt
- 返回-1
让我们看看下面的实现,以便更好地理解:
示例
def solve(s, t): if(len(t) % len(s) != 0): return -1; cnt = int(len(t) / len(s)) s = s * cnt if(s == t): return cnt return -1 s = "tom" t = "tomtomtom" print(solve(s, t))
输入
"tom", "tomtomtom"
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
3
广告