Reverse-Words-in-a-String-III

第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的话就很简单了:

1
2
3
4
5
6
7
8
9
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
words = s.split()
for i in range(len(words)):
words[i] = words[i][::-1]
return ' '.join(words)

然后是dicuss中的c解法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void reverse(int b, int e, char *s){
while(b < e) {
s[b] = s[b] ^ s[e];
s[e] = s[b] ^ s[e];
s[b] = s[b] ^ s[e];
b++;
e--;
}
}

char* reverseWords(char* s) {
int i, s_len = strlen(s), index = 0;

for(i = 0; i <= s_len; i++) {
if((s[i] == ' ') || (s[i] == '\0')){
reverse(index, i - 1, s);
index = i + 1;
}
}
return s;
}