はじめに
LeetCodeの問題を解答します。
なるべく、問題の和訳と詳細なコメントを書いています。
余裕があれば、複数のアプローチの解答と、実際の面接を想定して英語での解法やコメントを書いています。
様々なカテゴリの問題をランダムにあたる方法も良いですが、
二分探索、連結リストなど、テーマを絞って集中的に解いた方が練習しやすい方は以下の記事が有用です。
テーマごとに問題を分類しました。
LeeetCodeの問題をアルゴリズムとデータ構造による分類しました。
また、LeetCodeではAtcoderと違ってクラスと関数を定義して解答します。
LeetCodeに特有の内容など、知っておくと役に立つかもしれないことをまとめています。
はじめてLeetCodeに触れる方はこちらの記事も役に立つと思います。
ポイント
-
- 文字列とリスト(配列)の扱い
- 文字列とリストの変換
詳細
問題
原文
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:
12 Input: s = "the sky is blue"Output: "blue is sky the"Example 2:
123 Input: s = " hello world "Output: "world hello"Explanation: Your reversed string should not contain leading or trailing spaces.Example 3:
123 Input: s = "a good example"Output: "example good a"Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
Constraints:
1 <= s.length <= 104
s
contains English letters (upper-case and lower-case), digits, and spaces' '
.- There is at least one word in
s
.
Follow-up: If the string data type is mutable in your language, can you solve it in-place with
O(1)
extra space?
内容(和訳)
与えられた入力文字列sを単語の順序を逆にします。
単語はスペース以外の文字のシーケンスと定義されます。s内の単語は少なくとも1つのスペースで区切られます。
単語を逆の順序で、単一のスペースで連結した文字列を返します。
sには前後のスペースや単語間の複数のスペースが含まれる可能性があることに注意してください。返される文字列には単語を区切るための単一のスペースのみが含まれるようにします。余分なスペースは含めません。
※cahtGPTによる翻訳
解答
解答1:Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class Solution: def reverseWords(self, s: str) -> str: #戻り値用のリストを用意 reversed_words = [] #1単語を保持する変数 word = "" #sを一巡する for i in range(len(s)): #wordに文字があり、i番目の文字が空白の場合 if word and s[i]==" ": #戻り値用のリストにwordを追加 reversed_words.append(word) #wordを空文字に戻して次の単語を保持する準備をする word = "" #i番目の文字が空白以外の場合 elif s[i]!=" ": #wordにその文字を追加 →blu + e →blue word += s[i] #走査終了後、wordに文字があれば、戻り値用のリストに追加 if word: reversed_words.append(word) #リストを逆順にして空白区切りの文字列で返す return " ".join(reversed_words[::-1]) |
終わりに
補足・参考・感想
問題を分類しました。テーマごとに集中して問題を解くことができます。
LeeetCodeの問題をアルゴリズムとデータ構造による分類
LeetCodeに特有の内容など、知っておくと役に立つかもしれないことをまとめました。
疑問が解決した方は他の問題もどうぞ
前:1431. Kids With the Greatest Number of Candies
コメント