Code & Func
2017-12-15

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

然后是dicuss中的c解法:

1
void 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
11
char* 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
}
上一条动态