I was doing a problem on Leetcode - here is the problem:
Write a function that reverses a string. The input string is given as an array of characters char[]. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. You may assume all the characters consist of printable ascii characters.
My solution is
def reverseString(s): """ Do not return anything, modify s in-place instead. """ temp = "" for index,value in enumerate(s): temp+=value s.clear() for i in "".join(reversed(temp)): s.append(i) reverseString(["h","e","l","l","o"])
My solution works and is accepted by Leetcode. It also passes all the test cases. However, I am still new to the concept of space and time and was not sure if my solution follows the requirements of O(1) and modifies the array in place. If someone could confirm if it does or not and also teach me how to confirm this, it would be helpful. Thank you!
https://stackoverflow.com/questions/65386311/how-to-confirm-if-my-answer-has-o1-space-complexity-and-in-modification-of-an December 21, 2020 at 08:55AM
没有评论:
发表评论