左旋轉字符串


題目:定義字符串的左旋轉操作,把字符串前面的若干個字符移動到字符串的尾部。

要求:對長度為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;
}

運行界面如下:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM