问题
I have written different python codes to reverse a given string. But, couldn't able to figure the which one among them is efficient. Can someone point out the differences between these algorithms using time and space complexities?
def reverse_1(s):
result = ""
for i in s :
result = i + result
return result
def reverse_2(s):
return s[::-1]
There are already some solutions out there, but I couldn't find out the time and space complexity. I would like to know how much space s[::-1]
will take?
回答1:
Without even trying to bench it (you can do it easily), reverse_1
would be dead slow because of many things:
- loop with index
- constantly adding character to string, creating a copy each time.
So, slow because of loop & indexes, O(n*n)
time complexity because of the string copies, O(n)
complexity because it uses extra memory to create temp strings (which are hopefully garbage collected in the loop).
On the other hand s[::-1]
:
- doesn't use a visible loop
- returns a string without the need to convert from/to list
- uses compiled code from python runtime
So you cannot beat it in terms of time & space complexity and speed.
If you want an alternative you can use:
''.join(reversed(s))
but that will be slower than s[::-1]
(it has to create a list so join
can build a string back). It's interesting when other transformations are required than reversing the string.
Note that unlike C or C++ languages (as far as the analogy goes for strings) it is not possible to reverse the string with O(1)
space complexity because of the immutability of strings: you need twice the memory because string operations cannot be done in-place (this can be done on list of characters, but the str
<=> list
conversions use memory)
回答2:
Complexity
Operation | Example | Class | Notes
--------------+--------------+---------------+-------------------------------
Iteration | for v in l: | O(N) | Worst: no return/break in loop
Slice | l[a:b] | O(b-a) | l[1:5]:O(l)/l[:]:O(len(l)-0)=O(N)
The second one is better!
Source: https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt
来源:https://stackoverflow.com/questions/51335422/reverse-string-time-and-space-complexity