-
Notifications
You must be signed in to change notification settings - Fork 5
/
day-168.cpp
39 lines (29 loc) · 873 Bytes
/
day-168.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*
Length of Last Word
Given a string s consists of upper/lower-case alphabets and empty space
characters ' ', return the length of last word (last word means the last
appearing word if we loop from left to right) in the string.
If the last word does not exist, return 0.
Note: A word is defined as a maximal substring consisting of non-space
characters only.
Example:
Input: "Hello World"
Output: 5
*/
// Simple O(N) time & O(1) memory solution
// Beats 92.11 % of cpp submissions.
class Solution {
public:
int lengthOfLastWord(string s) {
int N = s.length();
int start = N - 1;
int answer = 0;
while (start >= 0 && s[start] == ' ') start -= 1;
if (start < 0) return answer;
while (start >= 0 && s[start] != ' ') {
answer += 1;
start -= 1;
}
return answer;
}
};