右旋 函數

來源:互聯網
上載者:User

標籤:右旋函數的實現

題目:輸入一個字串,將其進行右旋,如輸入“abcdef”,右旋二個將得到"efabcd",此題有多種解法,這裡介紹兩種常用的

字元右旋實現:(1)三步反轉法;(2)直接移動法

(1)三步反轉法:1)"abcd"->"dcba";

                 2)"ef"->"fe";  此時得到"dcbafe"

                 3)"dcbafe"->"efabcd";

(2)直接移動法:建立一個臨時變數存放最後一個字元,然後將剩餘所有的字元向後移動,最後將臨時變數中存放的字元放入空出來的打一個位置中,如此迴圈n次;

(1)三步反轉法# include <stdio.h># include <string.h># include <assert.h>void Reverse(char* start, char* end){assert(start);assert(end);while (start < end){char tmp = *start;*start = *end;*end = tmp;start++;end--;}}void RightLoopMove(char* pStr, size_t n){int len = strlen(pStr);Reverse(pStr, pStr + len - n - 1);Reverse(pStr+len-n, pStr + len - 1);Reverse(pStr, pStr + len- 1);}int main(){char arr[] = "abcdef";RightLoopMove(arr, 2);printf("%s\n", arr);system("pause");return 0;}(2)直接移動法# include <stdio.h># include <string.h># include <assert.h>RightLoopMove(char* pStr, size_t n){assert(pStr);int len = strlen(pStr);while (n){char tmp = pStr[len-1];for (int i = len-1; i >0; i--){pStr[i] = pStr[i - 1];}pStr[0] = tmp;n--;}}int main(){char arr[] = "abcdef";RightLoopMove(arr, 2);printf("%s\n", arr);system("pause");return 0;}


本文出自 “magoYang” 部落格,謝絕轉載!

右旋 函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.