题目
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