题目大意:独立反转字符串中的每个单词。
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:
1 2 |
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.
Idea: Brute Force
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Author: Huahua // Running time: 23 ms class Solution { public: string reverseWords(string s) { int index = 0; for (int i = 0; i <= s.length(); ++i) { if (i == s.length() || s[i] == ' ') { std::reverse(s.begin() + index, s.begin() + i); index = i + 1; } } return s; } }; |
Python3
1 2 3 4 5 6 7 |
""" Author: Huahua Running time: 44 ms (beats 100%) """ class Solution: def reverseWords(self, s): return ' '.join(map(lambda x: x[::-1], s.split(' '))) |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment