第 10 題(字符串)
翻轉句子中單詞的順序。
題目:輸入一個英文句子,翻轉句子中單詞的順序,但單詞內字符的順序不變。
句子中單詞以空格符隔開。為簡單起見,標點符號和普通字母一樣處理。
例如輸入“I am a student.”,則輸出“student. a am I”。
思路:用棧,把每個單詞壓入棧,再依次彈出輸出。
/* 第 10 題(字符串) 翻轉句子中單詞的順序。 題目:輸入一個英文句子,翻轉句子中單詞的順序,但單詞內字符的順序不變。 句子中單詞以空格符隔開。為簡單起見,標點符號和普通字母一樣處理。 例如輸入“I am a student.”,則輸出“student. a am I”。 start time 15:12 end time 15:39 */ #include <iostream> #include <vector> using namespace std; typedef struct Words{ int len; char * start; }Words; void reverseSentence(char * c) { vector<Words> S; //存儲單詞的棧 Words w; w.start = c; w.len = 0; for (int i = 0; c[i] != '\0'; i++) { if (c[i] != ' ') { w.len++; } else { if (w.len != 0) { S.push_back(w); w.start = c + i + 1; w.len = 0; } else //跳過多余的空格 { w.start = c + i + 1; } } } if (w.len != 0) //壓入最后一個詞 { S.push_back(w); } while (!S.empty()) { Words w = S.back(); for (int i = 0; i < w.len; i++) { cout << *(w.start + i); } cout << ' '; S.pop_back(); } cout << endl; } int main() { char * c = " I am a student."; reverseSentence(c); return 0; }
網上找答案,發現我的方法空間復雜度很高,O(n)網上通用的方法是原地翻轉句子,再把每個單詞翻轉回來。
http://www.cnblogs.com/yanhaiming/archive/2012/07/17/2595817.html
#include<iostream> #include<vector> #include<assert.h> #include<cstring> using namespace std; void swap(char &a, char &b) { char tmp = b; b = a; a = tmp; } void swap_str(char* str, int start, int end) { assert(str!=NULL && start <= end); int low = start; int high = end; //整個句子按字符翻轉 while (low < high) { swap(str[low], str[high]); low++; high--; } } //方法一:依次讀入句子中的每個單詞,並將它們放入一個棧中。然后再將單詞出棧。 //時間復雜度:O(n),空間復雜度:O(n); //方法二:首先將整個句子按字符翻轉,然后再將其中每個單詞的字符旋轉。 //時間復雜度:O(n),空間復雜度:O(1); void reverse_word(char str[]) { int len = strlen(str); //翻轉整個句子 swap_str(str, 0, len-1); int s = 0; int e = 0; //翻轉每個單詞 for (int i=0; i<len; i++) { e = i; if (str[e] == ' ') { //str[e]為空格,所以范圍是[s,e-1]. swap_str(str, s, e-1); s = e + 1; } } } int main() { char str[] = "I am a student."; reverse_word(str); cout<<str<<endl; return 0; }