剑指Offer之左旋转字符串(Move!Move!!Move!!!)

简介:

题目描述:
汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
输入:
多组测试数据,每个测试数据包含一个字符序列S和非负整数K。其中S的长度不超过1000。
输出:
对应每个测试案例,输出新序列。
样例输入:
UDBOJ 4
abba 1
样例输出:
JUDBO
bbaa
【解析】


思路源于前一篇文章思路:反转单词顺序

【代码】

/*********************************
*   日期:2013-12-02
*   作者:SJF0115
*   题号: 题目1362:左旋转字符串(Move!Move!!Move!!!)
*   来源:http://ac.jobdu.com/problem.php?pid=1362
*   结果:AC
*   来源:剑指Offer
*   总结:
**********************************/
#include <stdio.h>
#include <malloc.h>
#include <string.h>

char *str;

//反转单词
void ReverseWord(char* words,int begin,int end){
    int temp;
    if(words == NULL || begin > end || begin < 0){
        return;
    }
    //反转
    while(begin < end){
        temp = words[begin];
        words[begin] = words[end];
        words[end] = temp;
        begin ++;
        end --;
    }
}

char* Reverse(char* str,int n){
    if(str == NULL || n < 0){
        return "";
    }
    int len = strlen(str);
    //分成两部分(1)前n项(2)剩余项
    //反转前n个
    ReverseWord(str,0,n-1);
    //反转剩余
    ReverseWord(str,n,len-1);
    //全部反转
    ReverseWord(str,0,len-1);
    return str;
}


int main() {
    int i,n;
    str = (char*)malloc(sizeof(char)*1001);
    while(scanf("%s",str) != EOF){
        scanf("%d",&n);
        //左旋转
        //注意一下n需要取余就可以了,不能超过字符串自身的长度
        n = n % strlen(str);
        str = Reverse(str,n);
        //输出
        for(i = 0;i < strlen(str);i++){
            printf("%c",str[i]);
        }
        printf("\n");
    }//while
    return 0;
}


目录
相关文章
|
6月前
|
算法 C++
【C++11算法】move和move_backward
【C++11算法】move和move_backward
|
8月前
|
数据库
MOVE
MOVE
62 0
|
算法 Python
LeetCode 283. 移动零 Move Zeroes
LeetCode 283. 移动零 Move Zeroes
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
LeetCode 283. Move Zeroes
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
64 0
LeetCode 283. Move Zeroes
LeetCode之Move Zeroes
LeetCode之Move Zeroes
80 0
|
索引 Python Java
LeetCode 283:移动零 Move Zeroes
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. 示例: 输入: [0,1,0,3,12] 输出: [1,3,12,0,0] 说明: 必须在原数组上操作,不能拷贝额外的数组。
743 0