C語言左旋轉字串與翻轉字串中單詞順序的方法_C 語言

來源:互聯網
上載者:User

左旋轉字串
題目:

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

如把字串 abcdef  左旋轉 2  位得到字串 cdefab。請實現字串左旋轉的函數。

要求時間對長度為 n  的字串操作的複雜度為 O(n),輔助記憶體為 O(1)。

分析:

網上看到解法很多種,就不詳細說明了。

我採用的是數組不對稱的交換時間複雜度應該是O(n)。

代碼實現(GCC編譯通過):

#include "stdio.h"#include "stdlib.h" void reverse_str(char str[],int n,int m); int main(void){  char str[] = "abcdef";  reverse_str(str,6,2);  return 0;} //str為字串數組,n為數組長度,m為左移位元void reverse_str(char str[],int n,int m){  int i,j;  char tmp;        for(i=0,j=n-1;i<j;i++,j--)  {    tmp = str[i];    str[i] = str[j];    str[j] = tmp;  }   for(i=0,j=n-m-1;i<j;i++,j--)  {    tmp = str[i];    str[i] = str[j];    str[j] = tmp;  }   for(i=n-m,j=n-1;i<j;i++,j--)  {    tmp = str[i];    str[i] = str[j];    str[j] = tmp;  }   printf("%s\n",str);}


翻轉句子中單詞順序
翻轉句子中單詞的順序。

題目:

輸入一個英文句子,翻轉句子中單詞的順序,但單詞內字元的順序不變。

句子中單詞以空格符隔開。為簡單起見,標點符號和普通字母一樣處理。

例如輸入“I am a student.”,則輸出“student. a am I”。

這個題比較簡單,直接上代碼了(GCC編譯通過)

代碼實現:

#include "stdio.h"#include "stdlib.h" void helper(char a[],int n); int main(void){  char str[15] = "I am a student!";  helper(str,15);  printf("\n");  return 0;} void helper(char a[],int n){  int e = n-1;  int i,j,t;     for(i=e;i>=0;i=j-1)  {    for(j=i;j>=0 && a[j]!=' ' ;--j);    t=j+1;    while(t<=i)      printf("%c",a[t++]);    if(j<0)      return;    else        printf(" ");  }}

聯繫我們

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