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) 
  • 相关阅读:
    博客园风格简单修饰(Do It Yourself)
    十大经典排序算法
    物流BOS
    算法设计
    牛客网刷题
    关于上网的问题
    Lucene&Solr
    SSM综合练习
    四十八:WAF绕过-权限控制之代码混淆及行为造轮子
    四十七:WAF绕过-漏洞发现之代理池指纹被动探针
  • 原文地址:https://www.cnblogs.com/bozhou/p/6934731.html
Copyright © 2011-2022 走看看