tinycodinglm / cp /cp-10062.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 12)
3c88a0f verified
|
Raw History Blame Contribute Delete
1.72 kB
opencode trace
System You are an expert LeetCode problem solver. You solve problems efficiently with clean code.

You are an expert LeetCode problem solver. You solve problems efficiently with clean code.

User

Problem: Reverse Words in a String III (Difficulty: Easy)
Tags: Two Pointers, String

Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:
Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Example 2:
Input: s = "Mr Ding"
Output: "rM gniD"

Constraints:

  • 1 <= s.length <= 5 * 10^4
  • s contains printable ASCII characters.
  • s does not contain any leading or trailing spaces.
  • There is at least one word in s.
  • All the words in s are separated by a single space.
Assistant

Time: O(n)

Space: O(1)

class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
def reverse(s, begin, end):
for i in range((end - begin) // 2):
s[begin + i], s[end - 1 - i] = s[end - 1 - i], s[begin + i]

markdown
s, i = list(s), 0
    for j in range(len(s) + 1):
        if j == len(s) or s[j] == ' ':
            reverse(s, i, j)
            i = j + 1
    return "".join(s)

class Solution2(object):
def reverseWords(self, s):
reversed_words = [word[::-1] for word in s.split(' ')]
return ' '.join(reversed_words)