【问题标题】:Runtime for finding smallest common divisor of 2 strings查找 2 个字符串的最小公约数的运行时
【发布时间】:2021-09-27 14:49:20
【问题描述】:

我在这里尝试了这个问题:How to determine the smallest common divisor of a string?

我认为我的实现是正确的,但我不确定时间和空间的复杂性。两者似乎都是线性的。然而,第一次 for 循环检查让我对时间复杂度感到失望。 StringBuilder 对于空间复杂度也很棘手。

这是我编写的代码:

public static void main(String[] args) {
    String s1 = "bcdbcdbcdbcd", t1 = "bcdbcd";
    String s2 = "bcdbcdbcd", t2 = "bcdbcd";
    String s3 = "lrbb", t3 = "lrbb";
    System.out.println(getLength(s1, t1));
    System.out.println(getLength(s2, t2));
    System.out.println(getLength(s3, t3));
}

private static int getLength(String s, String t) {
    if(s.length() % t.length() > 0)
        return -1;
    StringBuilder sb = new StringBuilder();
    for(int i=0;i*t.length() < s.length();i++) {
        sb.append(t);
    }
    if(!sb.toString().equals(s))
        return -1;
        
    int divisible = 1;
    
    for(int i=1;i<=t.length();i++) {
        
       if(t.length()%divisible++ != 0) {
            continue;
        }
         
        sb = new StringBuilder();
        String subStr = t.substring(0, i);
        while(sb.length() < t.length()) {
            sb.append(subStr);
        }
        if(sb.toString().equals(t))
            return i;
    }
    return -1;
}

【问题讨论】:

    标签: java string time-complexity big-o space-complexity


    【解决方案1】:

    当前实现的复杂性:

    设n=|s|, m=|t|

    时间:

    O(n/m+m^2)
    

    空格:

    O(n+m)
    

    【讨论】:

      猜你喜欢
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多