[LeetCode] 151. Reverse Words in a String

Semidragon·2023년 8월 9일
0

CodingTest

목록 보기
6/80

1. Question

Given an input string s, reverse the order of the words.

A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.

Return a string of the words in reverse order concatenated by a single space.

Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.

Example 1:

Input: s = "the sky is blue"
Output: "blue is sky the"

2. Thoughts

  1. use split() to split the string into list
  2. ignore all "" and " "
  3. traverse the list reversely and append word revesely
  4. make it back to string using join()

3. Tips learned

3.1 Traverse list reversely using reversed()

Thus, you cannot do

a = ["foo", "bar", "baz"]
for i in reversed(a):
	print(i)
... 
>>> baz
>>> bar
>>> foo

4. My solution

class Solution:
    def reverseWords(self, s: str) -> str:
        ans = []
        for word in reversed(s.split(" ")):
            if word == " " or word == "":
                continue
            ans.append(word)

        return " ".join(ans)

5. AI Solution and Improvements

5.1. Refactoring the given code:

There are some issues and redundant checks in your code. Here's a more Pythonic version with comments explaining the changes:

class Solution:
    def gcdOfStrings(self, str1: str, str2: str) -> str:
        # Order strings by length
        shorter, longer = sorted([str1, str2], key=len)

        # Check for common prefix which divides both strings
        for i in range(len(shorter), 0, -1):  # Starting from the full length of shorter string and decreasing
            if shorter[:i] * (len(str1) // i) == str1 and shorter[:i] * (len(str2) // i) == str2:
                return shorter[:i]
                
        return ""

The code above directly checks for common prefixes that divide both strings, from the longest possible prefix to the shortest.

5.2. Better solution:

1) Pythonic Improvement:
Instead of splitting by a single space, we can just use split() without any argument. This will split the string at any whitespace sequence and discard empty strings by default. This eliminates the need to check for empty strings in the loop.

Here's the improved code:

class Solution:
    def reverseWords(self, s: str) -> str:
        return ' '.join(reversed(s.split()))
profile
Semidragon's network [CS undergrad @ Sungkyunkwan University | Networks + System @ CSI]

0개의 댓글