简体   繁体   中英

Time complexity of the code below

I am trying to check the time complexity of the below simple program. The program replaces spaces in a string with '%20' .

  1. The loop to count spaces (O(1) time)

      foreach (char k in s) { if (k == ' ') { spaces_cnt++; } } 
  2. The loop to replace the spaces (O(n) where n is size of string)

      char[] c = new char[s.Length + spaces_cnt * 3]; int i = 0; int j = 0; while (i<s.Length) { if (s[i] != ' ') { c[j] = s[i]; j++; i++; } else { c[j] = '%'; c[j + 1] = '2'; c[j + 2] = '0'; j = j + 3; i++; } } 

So I am guessing it is a "O(n) + O(1)" solution. Please correct me if I am wrong.

The loop to count spaces takes O(n) , not O(1) , since you're iterating over – and performing a check on – each of the n characters in your string.

As you stated, the replacement loop takes O(n) . Two O(n) operations performed sequentially have a combined complexity of O(n) (constant factors are discarded in Big-O notation).

PS You know that you can achieve the equivalent of all your code using a single line?

s = s.Replace(" ", "%20");

Looks like you're trying to encode a string. If that's the case, you can use the UrlPathEncode () method. If you're only trying to encode spaces, use Replace() (as mentioned by Douglas).

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