-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLastWordofen.java
More file actions
31 lines (24 loc) · 798 Bytes
/
LastWordofen.java
File metadata and controls
31 lines (24 loc) · 798 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
25
26
27
28
29
30
31
public class LastWordofen{
public static int lengthOfLastWord(String s) {
int length = 0;
int i = s.length() - 1;
// Step 1: skip trailing spaces
while (i >= 0 && s.charAt(i) == ' ') {
i--;
}
// Step 2: count last word characters
while (i >= 0 && s.charAt(i) != ' ') {
length++;
i--;
}
return length;
}
public static void main(String[] args) {
String s1 = "Hello World";
String s2 = " fly me to the moon ";
String s3 = "luffy is still joyboy";
System.out.println(lengthOfLastWord(s1)); // Output: 5
System.out.println(lengthOfLastWord(s2)); // Output: 4
System.out.println(lengthOfLastWord(s3)); // Output: 6
}
}