[LeetCOde] Reverse Words in a String III
Posted immjc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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.
题目要求把一个含有空格符的字符串中的每个单词反转,就需要对整个字符串根据空格符进行分割。对每个分割的单词进行反转,用tmp保存每个单词的首位索引,需要考虑的是最后一个单词后面没有空格,这时就对其进行单独判断后再进行反转。
class Solution { public: string reverseWords(string s) { int count = 0, tmp = 0; for (int i = 0; i != s.size(); i++) { if (i == s.size() - 1) { int left = tmp, right = i; while (left <= right) swap(s[left++], s[right--]); } else if (s[i] != ‘ ‘) count = i; else { int left = tmp, right = count; while (left <= right) swap(s[left++], s[right--]); tmp = count + 2; count += 1; } } return s; } }; // 19 ms
巧妙的写法:通过迭代器用i, j记录每个单词首末两位的偏移进行反转。
class Solution { public: string reverseWords(string s) { for (int i = 0; i != s.size(); i++) { if (s[i] != ‘ ‘) { int j = i; for (; j != s.size() && s[j] != ‘ ‘; j++) {} reverse(s.begin() + i, s.begin() + j); i = j - 1; } } return s; } }; // 23 ms
python写法:‘sep‘.join(seq): 返回一个以分隔符sep连接各个元素后生成的字符串。 x[::-1]: 对每个字符串进行反转。 split(): 对整个字符串根据空字符进行分割。
class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ return ‘ ‘.join(x[::-1] for x in s.split()) # 82 ms
以上是关于[LeetCOde] Reverse Words in a String III的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] Reverse Words in a String II
Reverse Words in a String leetcode
Leetcode 151. Reverse Words in a String