题目链接: Reverse Words in s String
题目意思: 给定一个字符串,要求把字符串中的"单词"反转
1. 所谓"单词"指的的连续的非空白字符
2. 必须把前后缀空格去掉
3. 连续多个空格要合并为一个
代码
class Solution { public: void reverseWords(string &s); }; void Solution::reverseWords(string &s) { int stringSize = s.length(); if (stringSize == 0) { return; } int begin = 0; int end = stringSize-1; while (s[begin] == ' ' && (begin < stringSize)){ ++begin; } while (s[end] == ' ' && (end >= 0)){ --end; } string tmpString = ""; for (int i = begin; i <= end; ++i) { tmpString = tmpString + s[i]; } s = ""; int tmpStringSize = tmpString.length(); begin = 0; end = tmpStringSize; for (int i = tmpStringSize-1; i >= 0; --i) { if (tmpString[i] == ' ' || i == 0) { if (tmpString[i] == ' ') { begin = i; } else { begin = -1; } for (int j = begin+1; j < end; ++j) { s = s + tmpString[j]; } if (begin != -1 && (end-begin > 1)) { s = s + ' '; } end = begin; } }