Dare2Solve
To find the length of the last word in a string:
Initialization:
length
set to 0.i
starting from the end of the string.Skip Trailing Spaces:
i
backwards until a non-space character or the beginning of the string is encountered.Count Characters:
i
is greater than or equal to 0 and s[i]
is not a space:
length
and move i
backwards.Return Result:
length
.O(n), where n is the length of the string s
. This is because we iterate through the string once.
O(1), as we use only a constant amount of extra space.
This approach efficiently computes the length of the last word in a string, handling spaces and ensuring correctness based on the problem's requirements.
#include <string>
using namespace std;
class Solution {
public:
int lengthOfLastWord(string s) {
int length = 0;
int i = s.length() - 1;
// Skip trailing spaces
while (i >= 0 && s[i] == ' ') {
i--;
}
// Count the length of the last word
while (i >= 0 && s[i] != ' ') {
length++;
i--;
}
return length;
}
};
class Solution:
def lengthOfLastWord(self, s: str) -> int:
length = 0
i = len(s) - 1
# Skip trailing spaces
while i >= 0 and s[i] == ' ':
i -= 1
# Count the length of the last word
while i >= 0 and s[i] != ' ':
length += 1
i -= 1
return length
class Solution {
public int lengthOfLastWord(String s) {
int length = 0;
int i = s.length() - 1;
// Skip trailing spaces
while (i >= 0 && s.charAt(i) == ' ') {
i--;
}
// Count the length of the last word
while (i >= 0 && s.charAt(i) != ' ') {
length++;
i--;
}
return length;
}
}
/**
* @param {string} s
* @return {number}
*/
var lengthOfLastWord = function (s) {
let res = 0;
for (let i = s.length - 1; i >= 0; i--) {
if (s[i] != ' ') res++;
else {
if (res > 0) return res;
}
}
return res;
};