問題
原文
Given a string
s
consisting of words and spaces, return the length of the last word in the string.A word is a maximal substring consisting of non-space characters only.
内容
単語と空白を含む s が与えられます。最後の単語の長さを返してください。
単語は空白でない文字列のみを含む部分文字列です。(2行目はよくわかりませんでした。)
※正しくない可能性があります。
方針
・sの文字列の長さが0なら0を返す
・最後の部分にある空白を取り除く
・空白で分割してリストに格納し、リストの最後の文字列の長さを返す
解答
解答1
1 2 3 4 5 6 7 8 9 10 11 |
class Solution: def lengthOfLastWord(self, s: str) -> int: #sの長さが0なら0を返す if len(s)==0: return 0 #sの最後の空白を除外 s=s.strip() #sの各文字を半角空白で区切ってword_listに格納する word_list = s.split(" ") #word_listの最後の要素の長さを返す return len(word_list[-1]) |
解答2:Python, 英語コメント
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
""" Let me check my understand about this question. I need to answer the length of the word that is positioned last element except space. Right? > Yes. Ok. I wanna make assumption and test cases. Can we assume that the length of the variable "s" is within 10^4? >OK. Great. Next can we assume that does the variable "s" have at least one word in it? >Yes Perfect. Last, Can we assume that does the variable "s" is consist only words and spaces? >Yes Thank you. This is it. Let me add assumption if I make up another. >OK. So, next , I wanna think about test cases. I will write down them that I think it is worth to test. >OK. 1:One of simple cases that "s" has only Words. ["hello", "World"] 2:One of general cases that "s" has words and spaces. ["hello", " ", "world"] 3:One of general cases that "s" has space in most right element. ["hello", "World", " "] 4:It might be edge cases. "s" has only spaces. ["", ""] Can we add assumption that "s" has at least one element which is space or word? >OK. Thank you. So I'm thinking that assumptions and test cases are adequate. OK. Next, let's talk about how we solve this problem. First I'm thinking about brute force algorithm. This algorithm trarveses "s" once and if we find the last element, we return the length. But we traverse from most right element to most left element to find last word quickly. Time complexity of This approach is Big O of n. O(n) Space complexity of thin approach is Big O of 1. O(1) > OK """ class Solution: def lengthOfLastWord(self, s: str) -> int: #Split "s" by spaces and assign the variable "word_list". word_list = s.split(" ") #Initilize "element" which is going to be used as index as -1. element = -1 #Assign length of word_list to the varibale "count". count = len(word_list) #Start a while loop until most right word. while word_list[element] == "": #The variable "element" is decremented in each iterate. element -= 1 #return length of last word When find it. return len(word_list[element]) |
なるべくInterviewを意識して英語コメントを書いてみた。
LeetCodeではテストケースや制約は与えられるけど、実際の面接ではその辺も自分で仮定する必要があるらしい。
こういう時に使える英語の表現をストックしておく必要がある。
最初はbrute forceでよく、その後により適切な解について説明できるように、問題の練習自体も繰り返しやっておきたい。
補足・参考・感想
コメント