简体   繁体   中英

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.

Space Complexity: O(N), the space used building A+A.

But I don't understand it. Can anybody please explain?

Example 1: Input: A = 'abcde', B = 'cdeab' Output: true

Example 2: Input: A = 'abcde', B = 'abced' Output: 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. Any constant * N is still O(N).

Time complexity is N *N because of the time taken by contains() check. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM