-
Notifications
You must be signed in to change notification settings - Fork 0
/
length_of_last_word.cpp
51 lines (44 loc) · 1.16 KB
/
length_of_last_word.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
40
41
42
43
44
45
46
47
48
49
50
/*
* =====================================================================================
*
* Filename: length_of_last_word.cpp
*
* Description: Length of Last Word. Given a string s consists of upper/lower-case
* alphabets and empty space characters ' ', return the length of last
* word in the string.
*
* Version: 1.0
* Created: 02/19/19 12:00:08
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), [email protected]
* Organization:
*
* =====================================================================================
*/
#include <cstdio>
#include <string>
class Solution {
public:
int lengthOfLastWord(const std::string& str) {
int j = str.size() - 1;
while (j >= 0 && str[j] == ' ') {
j--;
}
int i = j;
while (i >= 0 && str[i] != ' ') {
i--;
}
return (j - i);
}
};
int main(int argc, char* argv[]) {
std::string str = "Hello World";
if (argc > 1) {
str = argv[1];
}
auto len = Solution().lengthOfLastWord(str);
printf("Input: `%s`\nLength of last word: %d\n", str.c_str(), len);
return 0;
}