反转字符串中的单词 III
557. 反转字符串中的单词 III
给定一个字符串
s ,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
示例 1:
输入:s = "Let's take LeetCode contest" 输出:"s'teL ekat edoCteeL tsetnoc"
示例 2:
输入: s = "God Ding" 输出:"doG gniD"
提示:
1 <= s.length <= 5 * 104s包含可打印的 ASCII 字符。s不包含任何开头或结尾空格。s里 至少 有一个词。s中的所有单词都用一个空格隔开。
1 #include <iostream> 2 #include <algorithm> 3 using namespace std; 4 5 class Solution { 6 public: 7 string reverseWords(string s) { 8 string::iterator start = s.begin(); 9 for (string::iterator it = s.begin(); it != s.end(); it++) { 10 if (*it == ' ') { 11 reverse(start, it); 12 start = it + 1; 13 } 14 } 15 reverse(start, s.end()); 16 return s; 17 } 18 }; 19 20 int main() 21 { 22 Solution *test = new Solution(); 23 string s1 = "Let's take LeetCode contest"; 24 std::cout << "反转前:" << endl; 25 std::cout << s1 << endl; 26 string s2 = test->reverseWords(s1); 27 std::cout << "反转后:" << endl; 28 std::cout << s2 << endl; 29 system("pause"); 30 return 0; 31 }
浙公网安备 33010602011771号