Movatterモバイル変換


[0]ホーム

URL:


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

Commit6ed385c

Browse files
author
Vignesh Iyer
committed
Create : 58-Length-of-Last-Word
1 parent43119ae commit6ed385c

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

‎cpp/58-Length-of-Last-Word.cpp‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
classSolution {
2+
public:
3+
/*
4+
Approach:
5+
Traverse from end to the first whitespace character and count the number of letters.
6+
Return the count as our pointer hits the whitespace character.
7+
8+
Time complexity: O(n)
9+
Space complexity: O(1)
10+
*/
11+
intlengthOfLastWord(string s) {
12+
int n = s.length();
13+
14+
int ptr = n-1;
15+
while(ptr >=0 && s[ptr] =='') ptr--;/* Skip the trailing whitespaces*/
16+
17+
int len =0;
18+
while(ptr >=0 && s[ptr--] !='') len++;/* Counting the letters in the last word*/
19+
return len;
20+
}
21+
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp