zoukankan      html  css  js  c++  java
  • 左旋转字符串

    题目:定义字符串的左旋转操作,把字符串前面的若干个字符移动到字符串的尾部。

    要求:对长度为n的字符串操作的时间复杂度为O(n),辅助内存为O(1)。

    举例:把字符串abcdef左旋转2位得到字符串cdefab。

    答:

    #include "stdafx.h"
    #include <iostream>
    
    using namespace std;
    
    void swap(char *str, int begin, int end)
    {
        char ch;
        while (begin < end)
        {
            ch = *(str + begin);
            *(str + begin) = *(str + end);
            *(str + end) = ch;
            begin++;
            end--;
        }
    }
    
    void Rotate(char *str, int length ,int m)
    {
        if (NULL == str || length == 1)
        {
            return;
        }
        swap(str, 0, m - 1);
        swap(str, m, length - 1);
        swap(str, 0, length - 1);
    }
    
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        char chArr[] = "abcdef";
        char *p = chArr;
        cout<<p<<endl;
        Rotate(p, strlen(chArr), 2);
        cout<<p<<endl;
        return 0;
    }

    运行界面如下:

  • 相关阅读:
    python3第六天
    python3第五天
    python3第四天
    python3 第三天
    python3第二天
    python3(2)
    python3(1)
    网络通信 & 初识socket
    python中包的语法
    模块语法
  • 原文地址:https://www.cnblogs.com/venow/p/2655869.html
Copyright © 2011-2022 走看看