简体   繁体   English

如何确定旋转字符串算法的时空复杂度

[英]How to determine the Time and Space complexity of rotate string algorithm

Can anybody explain the time and space complexity for the below rotate string code snippet. 谁能解释下面的旋转字符串代码段的时间和空间复杂度。

The book from which this example is taken says that 引用此示例的书说:

Complexity Analysis 复杂度分析

Time Complexity: O(N^2), where N is the length of A. 时间复杂度:O(N ^ 2),其中N是A的长度。

Space Complexity: O(N), the space used building A+A. 空间复杂度:O(N),用于A + A的空间。

But I don't understand it. 但是我不明白。 Can anybody please explain? 有人可以解释吗?

Example 1: Input: A = 'abcde', B = 'cdeab' Output: true 示例1:输入:A ='abcde',B ='cdeab'输出:true

Example 2: Input: A = 'abcde', B = 'abced' Output: false 示例2:输入:A ='abcde',B ='abced'输出:false

public class RotateString {
public static void main(String[] args) {
    System.out.println(rotateString("abcd","dabc"));
}
 public static boolean rotateString(String a, String b) {
       return a.length()==b.length() && (a+a).contains(b);
 }

} }

Space complexity is O(N) because you are adding two strings of length N which will create a new string of length 2*N. 空间复杂度为O(N),因为要添加两个长度为N的字符串,这将创建一个新的长度为2 * N的字符串。 Any constant * N is still O(N). 任何常数* N仍为O(N)。

Time complexity is N *N because of the time taken by contains() check. 由于contains()检查所花费的时间,所以时间复杂度为N * N。 You are checking if string of length 2*N contains another string of length N. To do this using simple for loops, you will have to start checking at each of the 2*N positions and see if next N characters match the target string of length N. So number of comparisons would be 2*N times N = 2 * N ^ 2 ~= O(N^2). 您正在检查长度为2 * N的字符串是否包含另一个长度为N的字符串。要使用简单的for循环执行此操作,您将必须在2 * N个位置中的每个位置开始检查,看看接下来的N个字符是否与目标字符串N匹配。因此,比较次数将是2 * N乘以N = 2 * N ^ 2〜= O(N ^ 2)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何确定这两种算法的时空复杂度? - How to determine the space and time complexity of these two algorithms? 这个算法的时间和空间复杂度是多少? - What is the time and space complexity of this algorithm? 回文算法的时空复杂度 - Time and Space Complexity of Palindrome Algorithm 这种置换算法的时间和空间复杂度 - the time and space complexity of this permutation algorithm 如何确定这两种双链表算法的空间复杂度和时间复杂度? - How to determine the space and time complexity of these two double linked list algorithms? 如何为下面的新快速排序算法找到确切的时间复杂度和空间复杂度 - How to find exact Time complexity and Space Complexity for below new Quick sort algorithm ||的递归算法的时间复杂度和空间复杂度是多少? 操作员? - What is the time complexity and space complexity of a recursive algorithm with the || operator? 查找Anagrams的算法的时间复杂度和空间复杂度是多少? - What is the time complexity and space complexity of this algorithm to find Anagrams? 如何证明算法的时间复杂度? - How to justify the time complexity of an algorithm? Java 算法:分离奇偶数(时空复杂度) - Java Algorithm: Segregate Odd Even Numbers (time-space complexity)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM