forked from sureshmangs/Code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay-15-Length of Last Word.cpp
More file actions
70 lines (38 loc) · 1.04 KB
/
Day-15-Length of Last Word.cpp
File metadata and controls
70 lines (38 loc) · 1.04 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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
class Solution {
public:
int lengthOfLastWord(string s) {
reverse(s.begin(), s.end());
stringstream ss(s);
string tmp;
ss>>tmp;
return tmp.length();
}
};
class Solution {
public:
int lengthOfLastWord(string s) {
stringstream ss(s);
string tmp;
while(ss>>tmp);
return tmp.length();
}
};
class Solution {
public:
int lengthOfLastWord(string s) {
int tail=s.length()-1, len=0;
while(tail>=0 && s[tail]==' ')
tail--;
while(tail>=0 && s[tail]!=' '){
len++;
tail--;
}
return len;
}
};