題目
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
分析
字符串處理型。一種方法是從string中分析出每個單詞,需要考慮各種空格問題;另外一種是定義輸入流,把string作爲輸入流,每次讀取一個string,更加簡潔。
時間複雜度
第一種爲O(s.size());
輸入
空字符串需要特殊處理
""
" " / " "
"a" / "the sky is blue"
" a" /" the sky is blue"
" a "
結論
CODE1 : 48ms
CODE2 : 64ms
CODE3 : _
CODE2僅僅是把CODE1中的插入單詞作爲單獨的函數,函數調用使佔用時間增加?
CODE
CODE1
class Solution {
public:
void reverseWords(string &s) {
if(s.size() == 0) return;
string word, str;
bool flag = false;
for (auto c : s) {
if (!isspace(c)) {
if (flag == false) {
flag = true;
}
word += c;
} else {
if(flag == true) {
if(str.empty()) {
str = word;
} else {
str = word + " " + str;
}
word = "";
flag = false;
} else {
continue;
}
}
}
if (!isspace(s[s.size()-1])) {
if(str.empty()) {
str = word;
} else {
str = word + " " + str;
}
}
s = str;
}
};
class Solution {
public:
void reverseWords(string &s) {
if(s.size() == 0) return;
string word, str;
// flag: This poit is space?
// at the beginning, there is no word
bool flag = false;
for (auto c : s) {
if (!isspace(c)) {
if (flag == false) {
flag = true;
}
word += c;
} else {
if(flag == true) {
insertToString(str, word);
flag = false;
} else {
continue;
}
}
}
if (!isspace(s[s.size()-1])) {
insertToString(str, word);
}
s = str;
}
void insertToString(string &str, string &word) {
if(str.empty()) {
str = word;
} else {
str = word + " " + str;
}
word = "";
}
};
CODE3