Skip to content

Commit defa303

Browse files
authored
Create Length of Last Word
1 parent 1e6b228 commit defa303

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

Top Interview 150/Length of Last Word

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
想法:由後往前找,看到的第一個非空白的字母就開始紀錄往前連續幾個並回傳
2+
如果都沒有找到代表字串全部都是空白,回傳 0
3+
4+
Time Complexity : O(n) for traversing the string
5+
Space Complexity : O(1) for variables
6+
7+
class Solution {
8+
public:
9+
int lengthOfLastWord(string s) {
10+
for(int i = s.length() - 1 ; i >= 0 ; i--) {
11+
if ( s[i] == ' ' )
12+
continue ;
13+
int count = 0 ;
14+
while ( i >= 0 && s[i] != ' ') {
15+
count++ ;
16+
i-- ;
17+
}
18+
return count ;
19+
}
20+
return 0 ;
21+
}
22+
};

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy