Skip to content

Commit

Permalink
Create : 58-Length-of-Last-Word
Browse files Browse the repository at this point in the history
  • Loading branch information
Vignesh Iyer committed Nov 5, 2022
1 parent 43119ae commit 6ed385c
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions cpp/58-Length-of-Last-Word.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
class Solution {
public:
/*
Approach:
Traverse from end to the first whitespace character and count the number of letters.
Return the count as our pointer hits the whitespace character.
Time complexity: O(n)
Space complexity: O(1)
*/
int lengthOfLastWord(string s) {
int n = s.length();

int ptr = n-1;
while(ptr >= 0 && s[ptr] == ' ') ptr--; /* Skip the trailing whitespaces */

int len = 0;
while(ptr >= 0 && s[ptr--] != ' ') len++; /* Counting the letters in the last word */
return len;
}
};

0 comments on commit 6ed385c

Please sign in to comment.