Given a string s
consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0
.
A word is a maximal substring consisting of non-space characters only.
Example 1:
Input: s = "Hello World" Output: 5
Example 2:
Input: s = " " Output: 0
Constraints:
1 <= s.length <= 104
s
consists of only English letters and spaces' '
.
class Solution:
def lengthOfLastWord(self, s: str) -> int:
last_word_length = 0
meet_word = False
for i in range(len(s) - 1, -1, -1):
ch = ord(s[i])
if ch >= 65 and ch <= 122:
meet_word = True
last_word_length += 1
elif meet_word:
break
return last_word_length
class Solution {
public int lengthOfLastWord(String s) {
int n = s.length();
int lastWordLength = 0;
boolean meetWord = false;
for (int i = n - 1; i >= 0; --i) {
char ch = s.charAt(i);
if (ch >= 'A' && ch <= 'z') {
meetWord = true;
++lastWordLength;
} else if (meetWord) {
break;
}
}
return lastWordLength;
}
}
impl Solution {
pub fn length_of_last_word(s: String) -> i32 {
let s = s.trim_end();
if s.len() == 0 {
return 0;
}
for (i, c) in s.char_indices().rev() {
if c == ' ' {
return (s.len() - i - 1) as i32;
}
}
s.len() as i32
}
}