728x90
Top Interview Questions 의 Easy Collection에 있는 문제입니다.
문제는 여기서 볼 수 있습니다.
1. s를 뒤집어라.
2. s가 아닌 다른 변수를 만들어서 문제를 풀지 말고, s 자체를 바꾸어라.(in-place)
3. 메모리는 추가적으로 O(1)만 사용할 수 있다.
Example 1:
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
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.
풀이 방법
- case 1 : [::-1]를 사용하여 풀면 식도 간단하고, 계산 속도도 빠르다. 대신 s에 할당하는 것이 아니라, s[:]에 할당함으로써 문제의 제한사항을 어기지 않도록 한다.
- case 2 : 앞뒤의 문자열을 서로 바꾸어준다. 맨 앞, 뒤 문자열부터 시작해, 중간지점까지 서로 바꿔준다.
Code:
from typing import List
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
# case 1 : [:]를 활용해 in-place로 푼다 (case1가 case2보다 빠름)
# s[:] = s[::-1]
# case 2 : 양 끝의 원소를 서로 바꿔준다
for i in range(len(s)//2):
s[i], s[-1-i] = s[-1-i], s[i]
728x90
'알고리즘' 카테고리의 다른 글
[Leetcode/Python] Merge Two Sorted Lists (0) | 2022.08.21 |
---|---|
[Leetcode/Python] Valid Palindrome (0) | 2022.08.21 |
[Leetcode/Python] Count Primes (0) | 2022.08.18 |
[Leetcode/Python] 121. Best Time to Buy and Sell Stock (0) | 2022.08.17 |
[Leetcode/Python] Validate Binary Search Tree (0) | 2022.08.16 |