File size: 1,719 Bytes
3c88a0f | 1 2 3 4 5 | {"type": "session", "harness": "opencode", "id": "cp-10062", "name": "LeetCode 0557: Reverse Words In A String Iii"}
{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}
{"type": "message", "message": {"role": "user", "content": "Problem: Reverse Words in a String III (Difficulty: Easy)\nTags: Two Pointers, String\n\nGiven a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.\n\nExample 1:\nInput: s = \"Let's take LeetCode contest\"\nOutput: \"s'teL ekat edoCteeL tsetnoc\"\n\nExample 2:\nInput: s = \"Mr Ding\"\nOutput: \"rM gniD\"\n\nConstraints:\n- 1 <= s.length <= 5 * 10^4\n- s contains printable ASCII characters.\n- s does not contain any leading or trailing spaces.\n- There is at least one word in s.\n- All the words in s are separated by a single space."}}
{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def reverseWords(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n def reverse(s, begin, end):\n for i in range((end - begin) // 2):\n s[begin + i], s[end - 1 - i] = s[end - 1 - i], s[begin + i]\n\n s, i = list(s), 0\n for j in range(len(s) + 1):\n if j == len(s) or s[j] == ' ':\n reverse(s, i, j)\n i = j + 1\n return \"\".join(s)\n\n\nclass Solution2(object):\n def reverseWords(self, s):\n reversed_words = [word[::-1] for word in s.split(' ')]\n return ' '.join(reversed_words)\n\n"}}
|