NC269. 翻转单词序列
描述
示例1
输入:
"nowcoder. a am I"
输出:
"I am a nowcoder."
示例2
输入:
""
输出:
""
Rust 解法, 执行用时: 2ms, 内存消耗: 228KB, 提交时间: 2021-03-01
struct Solution{ } impl Solution { fn new() -> Self { Solution{} } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * @param ReverseSentence string字符串 * @return string字符串 */ pub fn ReverseSentence(&self, ReverseSentence: String) -> String { // write code here ReverseSentence.split(' ').into_iter().rev().collect::<Vec<_>>().join(" ") } }
C++ 解法, 执行用时: 2ms, 内存消耗: 356KB, 提交时间: 2021-04-30
class Solution { public: string ReverseSentence(string str) { string temp = ""; string ans = ""; int len = str.length(); for(int i=len-1;i>=0;i--) { if(str[i]!=' ') { temp=str[i]+temp; }else { ans += temp + ' '; temp = ""; } } if(temp.length()!=0) { ans += temp; } return ans; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 356KB, 提交时间: 2021-04-21
class Solution { public: string ReverseSentence(string str) { int left = 0, right = str.length()-1; while(right>=0 && str[right]==' ') right--; if(right == -1) return str; int len = right+1; str.resize(len); while(left < right) swap(str[ left++ ], str[ right-- ]); int i = left = 0; while(i < len) { if(str[i] == ' '){ right = i-1; while(left < right) swap(str[ left++ ], str[ right-- ]); left = ++i; continue; } i++; } right = i-1; while(left < right) swap(str[ left++ ], str[ right-- ]); return str; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 356KB, 提交时间: 2021-04-05
class Solution { public: string ReverseSentence(string str) { int len = 0, num = str.size(), pos = 0; vector<string> v; string st; //特殊情况1:字符串为空,则原样返回 if(str.empty()) return str; //特殊情况2:字符串全是空格,则原样返回 while(str[len] == ' ') len++; if(len == str.size()) return str; //普通判断,将字符串以空格为间隔拆分为多个字符串,之后再进行拼接 while(num > 0) { while(str[pos+len] != ' ' && num > 0) { len++; num--; } v.push_back(str.substr(pos,len)); num--; len++; pos += len; len = 0; } for(int i = v.size()-1; i >= 0; i--) { st.append(v[i]); st.append(" "); } st.erase(st.size()-1,1); return st; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 356KB, 提交时间: 2021-04-04
class Solution { public: string ReverseSentence(string str) { string res; string temp; for (auto c: str) { if (c == ' ') { res = temp + ' ' + res; temp = ""; } else { temp += c; } } res = temp + ' ' + res; res = res.substr(0, res.size() - 1); return res; } };