Skip to content

Commit 1cbb222

Browse files
Create length_of_last_word.cpp
1 parent b6abb1e commit 1cbb222

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

length_of_last_word.cpp

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#include <string.h>
2+
class Solution {
3+
private:
4+
static inline void rtrim(std::string &s) {
5+
s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) {
6+
return !std::isspace(ch);
7+
}).base(), s.end());
8+
}
9+
10+
public:
11+
int lengthOfLastWord(string s) {
12+
if(isspace(s[0]) and s.length() == 1) return 0;
13+
int cnt = 0;
14+
rtrim(s);
15+
for(int i=s.length()-1; i>=0; i--) {
16+
if(!isspace(s[i])) cnt++;
17+
else break;
18+
}
19+
return cnt;
20+
}
21+
};

0 commit comments

Comments
 (0)