Skip to content

Commit 6ed385c

Browse files
author
Vignesh Iyer
committed
Create : 58-Length-of-Last-Word
1 parent 43119ae commit 6ed385c

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+
class Solution {
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+
int lengthOfLastWord(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)