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.
难度评估:简单题
C++代码:
1 class Solution { 2 public: 3 //代码只考虑字符串每个word之间只有一个空格,且字符串首尾没有空格 4 string reverseWords(string s) { 5 for (int i = 0; i < s.length();) { 6 if (s[i] != ' ') { 7 int j = i; 8 while ((j < s.length()) && (s[j] != ' ')) { 9 ++j; 10 } 11 reverse(s.begin() + i, s.begin() + j); 12 i = j + 1; 13 } else { 14 ++i; 15 } 16 } 17 return s; 18 } 19 };
python3代码:
1 class Solution: 2 def reverseWords(self, s: str) -> str: 3 return ' '.join(s.split()[::-1])[::-1]