【編程題目】左旋轉字串 ☆

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   ar   for   div   art   

26.左旋轉字串(字串)
題目:
定義字串的左旋轉操作:把字串前面的若干個字元移動到字串的尾部。
如把字串 abcdef 左旋轉 2 位得到字串 cdefab。請實現字串左旋轉的函數。
要求時間對長度為 n 的字串操作的複雜度為 O(n),輔助記憶體為 O(1)。

 

思路:

設字串為 abcdefg 要左旋兩個, $$表示操作範圍,|表示要旋轉的軸線,將操作範圍分為兩個部分。每次把範圍小的部分與範圍大的部分的靠近|的位置交換。範圍相同則直接交換。

1. $ab|cdefg$

      2     5

2. cd$ab|efg$

          2    3

3. cdef&ab|g&

             2 1

4. cdef&a|g&b

           1   1

5. cdefgab       完成。

代碼用的遞迴實現。但是我不知道我用了迴圈中的int i和一些輔助的變數。是不是不符合輔助空間O(1)的要求了?

#include <stdio.h>#include <string.h>void swap(char * c1, char * c2){    char c = *c1;    *c1 = *c2;    *c2 = c;}void exchange(char * s1, char * s2, int n){    for(int i = 0; i < n; i++)    {        swap(s1,s2);        s1++;        s2++;    }}void rotate(char * in, int n, int len){    n = n % len; //判斷左旋字元數是否超過字串長度    int l = n, r = len - l;    if(l < r)    {        len -= l;        exchange(in, in + l, l);        rotate(in + l, l, len);    }    else if(l > r)    {        exchange(in + len - r, in + len - 2 * r, r);        len -= r;        rotate(in, len - r, len);    }    else    {        exchange(in, in + l, l);    }}void leftrotate(char * in, int n){    rotate(in, n, strlen(in));}int main(){    char s[] = "abcdefghi";    leftrotate(s, 10);    return 0;}

 

網上有個很巧妙的思路:

http://blog.sina.com.cn/s/blog_60c8379d010144w9.html

分析:如果將字串分為AB兩部分,其中A表示要移動到字串尾部的字串,B表示剩餘部分,我們先分別將A和B逆置,然後再將字串作為一個整體來逆置,這樣起到的效果是第一步先得到ATBT,然後得到(ATBT)T,即BA。

 

網上有STL的講解,還沒看http://blog.csdn.net/zhoushuai520/article/details/7703368

 

【編程題目】左旋轉字串 ☆

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.