标签:style blog class code c java
题目:
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return
"blue is sky the
".
解题思路:
1、先对字符串进行一次总的翻转
2、以空格为单位,划分单词,然后对每个单词再进行一次翻转
代码:
class Solution { public: void swap(char& a, char& b){ int tmp = a; a = b; b = tmp; } void reverse(string &s, int begin, int end){ if (s[begin] == ‘\0‘ || s[end] == ‘\0‘){ return; } while (begin < end){ swap(s[begin], s[end]); begin++; end--; } } void reverseWords(string &s) { if (s[0] == ‘\0‘ || s.empty()){ return; } reverse(s, 0, s.length() - 1); //*/ int start = 0, end = 0, len = 0; while (start < s.length()){ while (start != s.length() && s[start] == ‘ ‘) start++; //跳过对于的空格 for (end = start; end != s.length() && s[end] != ‘ ‘; end++); if (len != 0 && end > start) s[len++] = ‘ ‘; if (end > start){ reverse(s, start, end - 1); } while (start < end) s[len++] = s[start++]; } s.resize(len); //*/ } };
LeetCode OJ - Reverse Words in a String,布布扣,bubuko.com
LeetCode OJ - Reverse Words in a String
标签:style blog class code c java
原文地址:http://www.cnblogs.com/dongguangqing/p/3726260.html