LintCode Python 簡單級題目 8.旋轉字符串


題目描述:

給定一個字符串和一個偏移量,根據偏移量旋轉字符串(從左向右旋轉)

樣例

對於字符串 "abcdefg".

offset=0 => "abcdefg"
offset=1 => "gabcdef"
offset=2 => "fgabcde"
offset=3 => "efgabcd"
挑戰 

在數組上原地旋轉,使用O(1)的額外空間

題目分析:

題目原意是處理字符串,達到旋轉字符串的要求,首先的思路是Python的字符串切片操作,以offset為界,然后再拼接

class Solution:
    # @param s: a list of char
    # @param offset: an integer 
    # @return: nothing
    def rotateString(self, s, offset):
	    # write you code here
	    if not offset: return
	    if not s: return
	
	    n = len(s)
	    offset = offset%n # offset可能大於N,取offset模n的余數
	    
	    f = n - offset
	    return s[f:n]+s[0:f]

  

結果,題目傳入的是數組類型,需要直接處理原數組對象,而不是返回一個新的數組or字符串,so,更改如下:

class Solution:
    # @param s: a list of char
    # @param offset: an integer
    # @return: nothing
    def rotateString(self, s, offset):
        # write you code here
        if not offset: return
        if not s: return
        
        n = len(s)
        offset = offset%n
        
        for i in range(offset):
            t = s.pop()
            s.insert(0,t) 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM