题目链接:
https://www.lintcode.com/problem/1173/?_from=collection&fromId=208
描述:
给定一个字符串句子,反转句子中每一个单词的所有字母,同时保持空格和最初的单词顺序。
样例:
输入: Let's take LeetCode contest
输出: s'teL ekat edoCteeL tsetnoc
解题思路:
由样例可以看出先将字符串按空格分开后再进行反转,所以我们可以先将字符串按空格分割,
在C++中可以使用istringstream进行分割,用string的reverse(s.begin(),s.end())进行反转。
istringstream简单使用:
1、使用前必须包含头文件<sstream>2、构造istringstream:istringstream 变量名称(字符串/字符串变量);3、样例
#include<iostream> #include<sstream> //istringstream 必须包含这个头文件 #include<string> using namespace std; int main() { string str="123 456\n789"; istringstream is(str); string s; while(is>>s) // >> 按照字符流读入 所以是按' '或者'\n'分割 { cout<<s<<endl; } } 输出是: 123 456 789
#include<iostream> #include<sstream> //istringstream 必须包含这个头文件 #include<string> using namespace std; int main() { string str = "123/456/789"; istringstream is(str); string s; while(getline(is, s, '/')) // getline函数,自定义按照'/'分割 { cout<<s<<endl; } return 0; }
输出是:
123
456
789
所以该题我们可以这样写:
class Solution { public: /** * @param s: a string * @return: reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order */ string reverseWords(string &s) { if(s!=""){ //判断字符串是否为空 istringstream s1(s); //构造istringstream string s2; string s3; while (s1 >> s2) //按照字符流来截取 { reverse(s2.begin(), s2.end()); //先将截取的字符串进行反转 s3 = s3 + s2 + ' '; //相加并添加原句的空格 } s3.pop_back(); //因为在添加空格时在最后一个字符串末尾也加了空格,所以需要删除字符串最后的一个字符 return s3; } else return ""; } };