We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 43119ae commit 6ed385cCopy full SHA for 6ed385c
cpp/58-Length-of-Last-Word.cpp
@@ -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