難度簡單
字符串的左旋轉操作是把字符串前面的若干個字符轉移到字符串的尾部。請定義一個函數實現字符串左旋轉操作的功能。比如,輸入字符串"abcdefg"和數字2,該函數將返回左旋轉兩位得到的結果"cdefgab"。
示例 1:
輸入: s = "abcdefg", k = 2 輸出: "cdefgab"
示例 2:
輸入: s = "lrloseumgh", k = 6 輸出: "umghlrlose"
限制:
1 <= k < s.length <= 10000
分析:
用切片處理
考慮可能存在n>len(s)這種情況,因此求餘
時間複雜度:O(N)
空間複雜度:O(N)
class Solution(object): def reverseLeftWords(self, s, n): """ :type s: str :type n: int :rtype: str """ # 切片處理 if not s: return "" n = n % len(s) return s[n:] + s[:n]
執行用時 :8 ms, 在所有 Python 提交中擊敗了99.87%的用戶
內存消耗 :13 MB, 在所有 Python 提交中擊敗了100.00%的用戶