What is the runtime & space complexity of this Repeated Substring Pattern code? (Code is written in Java)

huangapple 未分类评论43阅读模式
英文:

What is the runtime & space complexity of this Repeated Substring Pattern code? (Code is written in Java)

问题

    public boolean repeatedSubstringPattern(String s) {
        if (s == null || s.isEmpty()) return true;
        int l = s.length();
        for (int i = l / 2; i > 0; --i) {
            if (l % i == 0 && isThisSubString(s, s.substring(0, i), l / i)) {
                return true;
            }
        }
        return false;
    }
    
    private boolean isThisSubString(String s, String subString, int m) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < m; ++i) {
            sb.append(subString);
        }
        return s.equals(sb.toString());
    }
}
英文:

I wrote this solution for LeetCode #459 problem. https://leetcode.com/problems/repeated-substring-pattern/
I want to know the runtime & space complexity of this solution.
I'm assuming runtime complexity of O(logN N) where N is the length of the String. Am I right?

    
    public boolean repeatedSubstringPattern(String s) {
        if (s == null || s.isEmpty()) return true;
        int l = s.length();
        for (int i = l / 2; i &gt; 0; --i) {
            if (l % i == 0 &amp;&amp; isThisSubString(s, s.substring(0, i), l / i)) {
                return true;
            }
        }
        return false;
    }
    
      private boolean isThisSubString(String s, String subString, int m) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i &lt; m; ++i) {
            sb.append(subString);
        }
        return s.equals(sb.toString());
    }

}

答案1

得分: 0

在最坏的情况下,当 i 等于 1 时,m 等于 5。isThisSubString 方法将遍历整个字符串。因此在最坏的情况下,渐近复杂度为 O(n^2)。

英文:

In the worst case when i is 1, m is equal to 5. isThisSubString method will be iterating over the entire string. So Asymptotically in the worst case, it is O(n^2).

huangapple
  • 本文由 发表于 2020年7月26日 05:13:58
  • 转载请务必保留本文链接:https://java.coder-hub.com/63093630.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定