leetcode 58 最後乙個單詞的長度

2021-10-03 11:49:25 字數 2006 閱讀 4627

題目描述:

給定乙個僅包含大小寫字母和空格 』 』 的字串 s,返回其最後乙個單詞的長度。

如果不存在最後乙個單詞,請返回 0 。

說明:乙個單詞是指僅由字母組成、不包含任何空格的最大子字串。

示例:

輸入: 「hello world」

輸出: 5

解題思路1:

遍歷每個字元以及對應的下標

當字元為空格時,記錄下當前的下標

遍歷完字串之後,取出最後乙個空格的下標

對應從字串中查詢最後乙個單詞即可

**1:

class

solution()

:def

lengthoflastword

(self, words):if

not words:

return

0 ret =

for index, word in

enumerate

(words)

:if word ==

' ':

temp = ret[-1

]return

len(words[temp+1:

])s = solution(

)words =

"hello world"

print

(s.lengthoflastword(words)

)

解題思路2:

字串從右往左遍歷,直到當前位置的元素為空

**2:

python

class

solution

(object):

deflengthoflastword

(self, words):if

not words:

return

0 words = words.strip(

)# 去掉首尾的字元

size =

len(words)

i =0while

(size-

1-i >=

0and words[size-

1-i]

!=' '):

i +=

1return i

s = solution(

)words =

"hello world"

print

(s.lengthoflastword(words)

)

c++

#include

#include

using

namespace std;

class

solution

size_t n = words.

find_last_not_of

(" \r\n\t");

// string::npos等於size_type型別可以表示的最大值,用來表示乙個不存在的位置

if(n != string::npos)

int size = words.

size()

;int i=0;

while

(size-

1-i>=

0&& words[size-

1-i]

!=' '

)return i;}}

;int

main()

[1]. leetcode–58–最後乙個單詞的長度

[2]. c++ 中string.erase() 的用法

[3]. std::string::npos的使用

LeetCode 58 最後乙個單詞的長度

給定乙個僅包含大小寫字母和空格 的字串,返回其最後乙個單詞的長度。如果不存在最後乙個單詞,請返回 0 說明 乙個單詞是指由字母組成,但不包含任何空格的字串。示例 輸入 hello world 輸出 5 usr bin python3 coding utf 8 time 2018 7 7 author...

LeetCode 58 最後乙個單詞的長度

今天開始保持記錄leetcode題.給定乙個僅包含大小寫字母和空格 的字串,返回其最後乙個單詞的長度。如果不存在最後乙個單詞,請返回 0 說明 乙個單詞是指由字母組成,但不包含任何空格的字串。示例 輸入 hello world 輸出 51 使用string.trim 方法首先刪除字串兩端的空格。2 ...

Leetcode 58 最後乙個單詞的長度

題目描述 給定乙個僅包含大小寫字母和空格 的字串,返回其最後乙個單詞的長度。如果不存在最後乙個單詞,請返回 0 說明 乙個單詞是指由字母組成,但不包含任何空格的字串。示例 輸入 hello world 輸出 5 解題思路 這個題是求最後乙個單詞的長度的,同時允許最後乙個單詞的後面有任意個空格,所以最...