C++實(shí)現(xiàn)LeetCode(557.翻轉(zhuǎn)字符串中的單詞之三)
[LeetCode] 557.Reverse Words in a String III 翻轉(zhuǎn)字符串中的單詞之三
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.
這道題讓我們翻轉(zhuǎn)字符串中的每個(gè)單詞,感覺(jué)整體難度要比之前兩道Reverse Words in a String II和Reverse Words in a String要小一些,由于題目中說(shuō)明了沒(méi)有多余空格,使得難度進(jìn)一步的降低了。首先我們來(lái)看使用字符流處理類stringstream來(lái)做的方法,相當(dāng)簡(jiǎn)單,就是按順序讀入每個(gè)單詞進(jìn)行翻轉(zhuǎn)即可,參見(jiàn)代碼如下:
解法一:
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(); return res; } };
下面我們來(lái)看不使用字符流處理類,也不使用STL內(nèi)置的reverse函數(shù)的方法,那么就是用兩個(gè)指針,分別指向每個(gè)單詞的開(kāi)頭和結(jié)尾位置,確定了單詞的首尾位置后,再用兩個(gè)指針對(duì)單詞進(jìn)行首尾交換即可,有點(diǎn)像驗(yàn)證回文字符串的方法,參見(jiàn)代碼如下:
解法二:
class Solution { public: string reverseWords(string s) { int start = 0, end = 0, n = s.size(); while (start < n && end < n) { while (end < n && s[end] != ' ') ++end; for (int i = start, j = end - 1; i < j; ++i, --j) { swap(s[i], s[j]); } start = ++end; } return s; } };
類似題目:
參考資料:
https://discuss.leetcode.com/topic/85773/nothing-fancy-straight-java-stringbuilder
https://discuss.leetcode.com/topic/85797/java-two-methods-3-line-using-built-in-and-char-array
到此這篇關(guān)于C++實(shí)現(xiàn)LeetCode(557.翻轉(zhuǎn)字符串中的單詞之三)的文章就介紹到這了,更多相關(guān)C++實(shí)現(xiàn)翻轉(zhuǎn)字符串中的單詞之三內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C語(yǔ)言實(shí)現(xiàn)鏈隊(duì)列基本操作
這篇文章主要為大家詳細(xì)介紹了C語(yǔ)言實(shí)現(xiàn)鏈隊(duì)列基本操作,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09c語(yǔ)言實(shí)現(xiàn)二叉查找樹(shù)實(shí)例方法
這篇文章主要介紹了一個(gè)c語(yǔ)言版的二叉查找樹(shù)實(shí)現(xiàn),二叉查找樹(shù),支持的操作包括:SERACH、MINIMUM、MAXIMUM、PREDECESSOR、SUCCESSOR、INSERT、DELETE,大家參考使用吧2013-11-11C++設(shè)計(jì)模式之適配器模式(Adapter)
這篇文章主要為大家詳細(xì)介紹了C++設(shè)計(jì)模式之適配器模式Adapter,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-03-03C語(yǔ)言程序中結(jié)構(gòu)體的內(nèi)存對(duì)齊詳解
這篇文章主要為大家詳細(xì)介紹了C語(yǔ)言程序中結(jié)構(gòu)體的內(nèi)存對(duì)齊的相關(guān)資料,文中的示例代碼講解詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴可以了解一下2022-11-11