Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit defa303

Browse files
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
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)

AltStyle によって変換されたページ (->オリジナル) /