《剑指offer》左旋转字符串

本题来自《剑指offer》 左旋转字符串

题目:

   汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!

思路:

   思路一:c++,操作字符,直接采用指针形式

  通过举个例子直白看,比如abcdefg 2,结果是cdefgab

  第一步将ab翻转。bacdefg

  第二步将后面的翻转。bagfedc

  第三步全部翻转便可得到。cdefgab

  思路二:python的字符串切片

C++ Code:

class Solution {
public:
    string LeftRotateString(string str, int n) {
        if (str.size()<=0){                    //boundary condition judgement
            return "";
        }
        char* begin = &str[0];                 //get the first pointer of str
        char* end = begin;                     //end pointer of str
        char* pn = begin;                      //top n pointer
        while(*end!='\0'){                     //get the end pointer
            end++;
        }
        end--;
        for (int i=0;i<n;i++){                 //get top n pointer
            pn++;
        }
        Reverse(begin,pn-1);                   //reverse top n character
        Reverse(pn,end);                       //reverse from n to end character
        Reverse(begin,end);                    //reverse all character
        return str;
    }
    void Reverse(char* begin,char* end){       //program of reverse
        if(begin==NULL||end==NULL){            //boundary condition judgement
            return ;
        }
        while(begin<end){
            char temp = *begin;                //swap value of str
            *begin = *end;
            *end = temp;
            begin++;                           //pointer increase
            end--;
        }
    }
};

Python Code:

# -*- coding:utf-8 -*-
class Solution:
    def LeftRotateString(self, s, n):
        # write code here
        if s:                        #boundary condition judgement
            for i in range(n):       #loop n times
                w1 = s[0]            #get first character of s
                s = s.lstrip(w1)     #strip character of the left s
                s += w1              #append character backwords
            return s                 #return result
        else:
            return ""                #if input parameters is empty,will return empty char
posted @ 2019-04-28 14:22  weilongyitian  阅读(293)  评论(0编辑  收藏  举报