# 557. Reverse Words in a String III 題目:<https://leetcode.com/problems/reverse-words-in-a-string-iii/> 解法一:使用內建的 split 方法,分割出所有單字,最後將每個單字反轉後串接。 Python3: ``` python 3 class Solution: def reverseWords(self, s: str) -> str: tokens = s.split(' ') output = tokens[0][::-1] for t in tokens[1:]: output += ' ' + t[::-1] return output if __name__ == '__main__': s = "Let's take LeetCode contest" ans = Solution().reverseWords(s) print(ans) ``` 解法二:直接解,找出各個單字的頭尾,將每個單字反轉回來。 C: ``` c #include <stdio.h> #include <stdlib.h> #include <string.h> char * reverseWords(char * s) { int len = strlen(s), check, start, end; // reverse word check = 0; while (check < len - 1) { while (s[check] == ' ') check++; start = check; while (s[check] != ' ' && s[check] != '\0') check++; end = check - 1; while (start < end) { char tmp = s[start]; s[start++] = s[end]; s[end--] = tmp; } } return s; } int main() { char s[] = "Let's take LeetCode contest"; char * ans = reverseWords(s); printf("%s|\n", ans); return 0; } ``` ###### tags: `leetcode` `string` `two pointers`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up