Python Algorithm Q2
Q2 Reverse-String
Q
Write a function that reverses a string. The input string is given as an array of characters s.
You must do this by modifying the input array in-place with O(1) extra memory.
Sample Input
Input: s = [“h”,”e”,”l”,”l”,”o”] Output: [“o”,”l”,”l”,”e”,”h”]
Input: s = [“H”,”a”,”n”,”n”,”a”,”h”] Output: [“h”,”a”,”n”,”n”,”a”,”H”]
Constraints
- 1 <= s.length <= 105
- s[i] is a printable ascii character.
1. My Solution
1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def reverseString(self, s: List[str]) -> None:
for i in range(len(s)//2):
a: str = s[i] #save first
print(a)
s[i]=s[-(i+1)]
print(s[i])
s[-(i+1)] = a
#for testing
s = Solution()
s.reverseString(["a","b","c","d"])
Simple Concept. Just saved the first element to temporary ‘a’ variable, and put the last element(s[-1]) to the first one(s[0]). Keep changing while the loop meets the center. I chose ‘len(s)//2’, since residue is useless. That’s because the center element don’t need to be changed.
In my solution, I have to be aware of the type of ‘s’. I put
s.reverseString("hello")
in my first try.
In this case, the type of ‘s’ become just string. not list comprise of string.
Therefore the error ‘TypeError: ‘str’ object does not support item assignment’ occurs. Be Careful! Python’s type hint is just the ‘hint’. It doesn’t define the type of the object.
2. Given Solution #1
1
2
3
4
5
6
def reverseString(self, s: List[str]) -> None:
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
No Commentary is needed for this solution.
3. Given Solution #2
According to the book, this is the ‘Pythonic’ way.
1
2
def reverseString(self, s: List[str]) -> None:
s.reverse()
Wow… the method ‘reverse’ is only provided when using the list.
When if the input is the string, U can use the string slicing method like s = s[::-1]
Overall Review
The solution that called ‘Pythonic’ way makes me shocked. Python library is literally amazing and contains incountable method. I should learn more to use python better.