LeetCode-Reverse_Words_in_a_String_III

題目:

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Note: In the string, each word is separated by single space and there will not be any extra space in the string.


翻譯:

給定一個字符串,你需要翻轉句子中每個單詞的字符順序同時保留空格和初始的單詞順序。

例子 1:

輸入: "Let's take LeetCode contest"
輸出: "s'teL ekat edoCteeL tsetnoc"

注意: 在字符串中,每個單詞都由一個空格分隔,並且字符串中沒有多餘的空格。


思路:

重點在於按空格對字符串進行分隔操作,見代碼。


C++代碼(Visual Studio 2017):

#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

class Solution {
public:
	string reverseWords(string s) {
		string res = "", t = "";
		istringstream is(s);
		while (is >> t) {        //這兩條語句是按空格分隔字符串
			reverse(t.begin(), t.end());
			res += t + " ";
		}
		res.pop_back();  //string.pop_back()刪除源字符串的最後一個字符,這裏去掉字符串的末尾空格
		return res;
	}
};
int main()
{
	Solution s;
	string str = "Let's take LeetCode contest";
	string result = s.reverseWords(str);
	cout << result<<endl;
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章