zoukankan      html  css  js  c++  java
  • 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) 
  • 相关阅读:
    Mybatis懒加载
    Mybatis 动态SQL
    Mybatis的多表查询
    linux selinux
    linux find/vi复制粘贴
    01-oracle限定查询-20190404
    awk
    sed
    windows删除指定日期前的文件
    win10 sshsecureshellclient删除profile保存的信息
  • 原文地址:https://www.cnblogs.com/bozhou/p/6934731.html
Copyright © 2011-2022 走看看