-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path58-length-of-last-word.js
59 lines (45 loc) · 1.53 KB
/
58-length-of-last-word.js
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
/**
* @param {string} s
* @return {number}
*/
// Solution: We want to want to iterate over each character
// in the string starting from the end (right to left) and
// then count the letters of the last word and return that
// stored count
var lengthOfLastWord = function(s) {
// Create an index that equals the last character in the array
let i = s.length - 1;
// Initialize a variable to count the letters in the last word
let lastWordLength = 0;
// In the case that there is one space or a bunch of spaces at the end
// of the input string, simply loop over them and decrement our index
// variable until we find the last letter of the last word
while (s[i] === " " && i >= 0) {
i--;
}
// Now that we have found the last letter, incrememnt our counter
// until we hit the next space, which tells us that we have reached
// the first letter of the last word - at that point we can exit
// the loop because we don't care about anything to the left of the
// last word in the input string
while (s[i] !== " " && i >= 0) {
lastWordLength++;
i--;
}
// Return the counter containing the number of letters in the last word
return lastWordLength;
};
/* Concise solution without comments:
var lengthOfLastWord = function(s) {
let i = s.length - 1;
let lastWordLength = 0;
while (s[i] === " " && i >= 0) {
i--;
}
while (s[i] !== " " && i >= 0) {
lastWordLength++;
i--;
}
return lastWordLength;
};
*/