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"
Thus, you cannot do
a = ["foo", "bar", "baz"]
for i in reversed(a):
print(i)
...
>>> baz
>>> bar
>>> foo
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)
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.
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()))