您好,登錄后才能下訂單哦!
這篇文章給大家介紹C++中如何使用LeetCode翻轉(zhuǎn)字符串中的單詞,內(nèi)容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
Given an input string , reverse the string word by word.
Example:
Input: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]
Note:
A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces.
The words are always separated by a single space.
Follow up: Could you do it in-place without allocating extra space?
這道題讓我們翻轉(zhuǎn)一個字符串中的單詞,跟之前那題 Reverse Words in a String 沒有區(qū)別,由于之前那道題就是用 in-place 的方法做的,而這道題反而更簡化了題目,因為不考慮首尾空格了和單詞之間的多空格了,方法還是很簡單,先把每個單詞翻轉(zhuǎn)一遍,再把整個字符串翻轉(zhuǎn)一遍,或者也可以調(diào)換個順序,先翻轉(zhuǎn)整個字符串,再翻轉(zhuǎn)每個單詞,參見代碼如下:
解法一:
class Solution { public: void reverseWords(vector<char>& str) { int left = 0, n = str.size(); for (int i = 0; i <= n; ++i) { if (i == n || str[i] == ' ') { reverse(str, left, i - 1); left = i + 1; } } reverse(str, 0, n - 1); } void reverse(vector<char>& str, int left, int right) { while (left < right) { char t = str[left]; str[left] = str[right]; str[right] = t; ++left; --right; } } };
我們也可以使用 C++ STL 中自帶的 reverse 函數(shù)來做,先把整個字符串翻轉(zhuǎn)一下,然后再來掃描每個字符,用兩個指針,一個指向開頭,另一個開始遍歷,遇到空格停止,這樣兩個指針之間就確定了一個單詞的范圍,直接調(diào)用 reverse 函數(shù)翻轉(zhuǎn),然后移動頭指針到下一個位置,在用另一個指針繼續(xù)掃描,重復(fù)上述步驟即可,參見代碼如下:
解法二:
class Solution { public: void reverseWords(vector<char>& str) { reverse(str.begin(), str.end()); for (int i = 0, j = 0; i < str.size(); i = j + 1) { for (j = i; j < str.size(); ++j) { if (str[j] == ' ') break; } reverse(str.begin() + i, str.begin() + j); } } };
關(guān)于C++中如何使用LeetCode翻轉(zhuǎn)字符串中的單詞就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。