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) 
  • 相关阅读:
    熟悉常用的HBase操作
    爬虫大作业
    熟悉常用的HDFS操作
    数据结构化与保存
    获取全部校园新闻
    爬取校园新闻首页的新闻的详情,使用正则表达式,函数抽离+网络爬虫基础练习
    中文词频统计
    英语词频统计
    AXIOS中文文档
    overload方法重载
  • 原文地址:https://www.cnblogs.com/bozhou/p/6934731.html
Copyright © 2011-2022 走看看