您好,登錄后才能下訂單哦!
這篇文章給大家介紹C++中如何使用LeetCode翻轉字符串中的單詞,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
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?
這道題讓我們翻轉一個字符串中的單詞,跟之前那題 Reverse Words in a String 沒有區別,由于之前那道題就是用 in-place 的方法做的,而這道題反而更簡化了題目,因為不考慮首尾空格了和單詞之間的多空格了,方法還是很簡單,先把每個單詞翻轉一遍,再把整個字符串翻轉一遍,或者也可以調換個順序,先翻轉整個字符串,再翻轉每個單詞,參見代碼如下:
解法一:
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 函數來做,先把整個字符串翻轉一下,然后再來掃描每個字符,用兩個指針,一個指向開頭,另一個開始遍歷,遇到空格停止,這樣兩個指針之間就確定了一個單詞的范圍,直接調用 reverse 函數翻轉,然后移動頭指針到下一個位置,在用另一個指針繼續掃描,重復上述步驟即可,參見代碼如下:
解法二:
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); } } };
關于C++中如何使用LeetCode翻轉字符串中的單詞就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。