soapyigu/LeetCode-Swift

Your Reverse String Solution Time Complexity is O(1)

MrPans opened this issue · 2 comments

as Apple API Reference say:

Swift Standard Library - AnyBidirectiona - lCollection

reversed()

Instance Method
reversed()
Returns a view presenting the elements of the collection in reverse order.
...
...
If you need a reversed collection of the same type, you may be able to use the collection’s sequence-based or collection-based initializer. For example, to get the reversed version of a string, reverse its characters and initialize a new String instance from the result.

let reversedWord = String(word.characters.reversed())
print(reversedWord)
// Prints "sdrawkcaB"

Complexity: O(1)

Hi,

Thank you for your advice. Currently I am using reverse() instead of reversed(). The previous one is a function of Swift 2.2 and the other is of Swift 3.0. The complexity of reverse() is O(n).

You can also check the code in the original Apple Swift repo, and will notice reverse() is implemented by a simple iteration accompanied with swap() function. Basically I guess the time complexity is O(n).

For more details, you can also reference the article here: http://vulgur.me/2016/07/03/leetcode-344/.

Thank you,
Yi

You're right. I've do some performance tests,The complexity of reverse() is close to O(n). Thanks for your reply.