-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0058-length-of-last-word.cpp
52 lines (49 loc) · 1.01 KB
/
0058-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
51
52
#include <vector>
#include <string>
#include <iostream>
using namespace std;
class Solution
{
public:
int lengthOfLastWord(string s)
{
int i = 0;
int search_start = 0;
int search_end = s.length() - 1;
while (i < s.length())
{
if (s[i] != ' ')
{
break;
}
i++;
search_start++;
}
i = s.length() - 1;
while (i > 0)
{
if (s[i] != ' ')
{
break;
}
i--;
search_end--;
}
vector<int> spaces;
for (int j = search_start; j < search_end + 1; j++)
{
if (s[j] == ' ')
{
spaces.push_back(j);
}
}
if (spaces.size() > 0)
return search_end - spaces[spaces.size() - 1];
return search_end - search_start + 1;
}
};
int main()
{
int j = (new Solution())->lengthOfLastWord(" a ");
cout << j;
}