[英]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.