LintCode_053_翻转字符串
2017-08-22 17:51
357 查看
问题描述
给定一个字符串,逐个翻转字符串中的每个单词。说明
单词的构成:无空格字母构成一个单词输入字符串是否包括前导或者尾随空格?可以包括,但是反转后的字符不能包括
如何处理两个单词间的多个空格?在反转字符串中间空格减少到只含一个
求解
首先将字符串整体翻转,然后逐个找到单词,再把单词翻转过来class Solution { public: /** * @param s : A string * @return : A string */ string reverseWords(string s) { // Reverse the whole string first. reverse(s.begin(), s.end()); std::string::size_type begin = 0, end = 0, len = 0; while ((begin = s.find_first_not_of(" ", end)) != string::npos) { if ((end = s.find(" ", begin)) == string::npos) { end = s.length(); } // Reverse each word in the string. reverse(s.begin() + begin, s.begin() + end); // Shift the word to avoid extra space. move(s.begin() + begin, s.begin() + end, s.begin() + len); len += end - begin; if(len < s.length()) { s[len++] = ' '; } } s.resize(len ? len - 1 : 0); return s; } };
相关文章推荐
- LintCode_053_翻转字符串
- 【LintCode】Reverse Words in a String 翻转字符串
- LintCode-53.翻转字符串
- LintCode【简单】53. 翻转字符串 。代码及思路
- lintcode,翻转字符串
- LintCode 第53题 翻转字符串
- Lintcode 翻转字符串
- 【LintCode】Reverse Words in a String 翻转字符串
- [LintCode] Reverse Words in a String 翻转字符串中的单词
- LintCode 53 翻转字符串
- 翻转字符串(LintCode)
- LintCode(easy)翻转字符串
- LintCode- 翻转字符串
- python_lintcode_52翻转字符串_128哈希函数
- LintCode 算法(简单)翻转字符串
- [LintCode]53.翻转字符串
- LintCode-剑指Offer-(53)翻转字符串
- [Lintcode] #53 翻转字符串
- LintCode 53. 翻转字符串
- 翻转子串(思路:假定两个字符串已经是翻转)