- Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathLengthofLastWord.java
More file actions
Latest commit
24 lines (24 loc) · 651 Bytes
/
Copy pathLengthofLastWord.java
File metadata and controls
24 lines (24 loc) · 651 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return
* the length of last word in the string.
*
* <p>If the last word does not exist, return 0.
*
* <p>Note: A word is defined as a character sequence consists of non-space characters only.
*
* <p>For example, Given s = "Hello World", return 5.
*/
publicclassLengthofLastWord {
publicintlengthOfLastWord(Strings) {
inti = s.length() - 1;
while (i >= 0 && s.charAt(i) == ' ') {
i--;
}
if (i < 0) return0;
intj = i;
while (j - 1 >= 0 && s.charAt(j - 1) != ' ') {
j--;
}
returni - j + 1;
}
}