November 16, 2023

Viiisit [LeetCode] - 58. Length of Last Word

#php#javascript#ruby

keep learning, keep coding!

Problem - Length of Last Word

Given a string s consisting of words and spaces, return the length of the last word in the string.

A word is a maximal substring consisting of non-space characters only.

翻譯蒟蒻

要回傳整個字串中的最後一個字母的長度。


Solution - JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* @param {string} s
* @return {number}
*/
var lengthOfLastWord = function(s) {
// 移除前後空白格
let trimmedString = s.trim();

let length = 0;
for (let i = trimmedString.length - 1; i >= 0; i--) {
if (trimmedString[i] === " ") {
break;
}
length++;
}

return length;
};

Solution - Ruby

1
2
3
4
5
6
7
8
9
10
11
12
def length_of_last_word(s)
# 用 strip 移除空白格
trimmed_s = s.strip
length = 0
(trimmed_s.length - 1).downto(0).each do |i|
if trimmed_s[i] == " "
break
end
length += 1
end
length
end

Solution - PHP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function lengthOfLastWord($s) {
$trimmedString = trim($s);
$length = 0;
for ($i = strlen($trimmedString) - 1; $i >= 0; $i--) {
if ($trimmedString[$i] === " ") {
break;
}
$length++;
}
return $length;
}

$s = "Hello World";
$result = lengthOfLastWord($s);
echo "Length of the last word: " . $result; // Length of the last word: 5

PHP 方法筆記

LeetCode 傳送門 - Length of Last Word