第79天。
今天的题目是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.
用python
的话就很简单了:
1def reverseWords(self, s):2 """3 :type s: str4 :rtype: str5 """6 words = s.split()7 for i in range(len(words)):8 words[i] = words[i][::-1]9 return ' '.join(words)
然后是dicuss
中的c
解法:
1void reverse(int b, int e, char *s){2 while(b < e) {3 s[b] = s[b] ^ s[e];4 s[e] = s[b] ^ s[e];5 s[b] = s[b] ^ s[e];6 b++;7 e--;8 }9}10
11char* reverseWords(char* s) {12 int i, s_len = strlen(s), index = 0;13
14 for(i = 0; i <= s_len; i++) {15 if((s[i] == ' ') || (s[i] == '\0')){6 collapsed lines
16 reverse(index, i - 1, s);17 index = i + 1;18 }19 }20 return s;21}