題目鏈接:
https ://www.lintcode.com/problem/1173/?_from=collection&fromId=208
描述:
給定一個字串句子,反轉句子中每一個單詞的所有字母,同時保持空格和最初的單詞順序,
樣例:
輸入 : Let's take LeetCode contesc
輸出 : 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
AC代碼:
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 "";
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/421616.html
標籤:其他
下一篇:小程式商城網站開發秒殺模塊篇
