-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathLengthOfLastWord.java
More file actions
38 lines (35 loc) · 961 Bytes
/
LengthOfLastWord.java
File metadata and controls
38 lines (35 loc) · 961 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
32
33
34
35
36
37
/**
Find length of last word in the given string...
**/
public class Solution {
// DO NOT MODIFY THE ARGUMENTS WITH "final" PREFIX. IT IS READ ONLY
public int lengthOfLastWord(final String A) {
String[] array = A.split(" ");
if(array.length == 0) return 0;
return array[array.length-1].length();
}
}
// Another solution for the problem by traversing through the end of the string
public class Solution {
public int lengthOfLastWord(final String a)
{
boolean char_flag = false;
int len = 0;
for (int i = a.length() - 1; i >= 0; i--) {
if (Character.isLetter(a.charAt(i))) {
// Once the first character from last
// is encountered, set char_flag to true.
char_flag = true;
len++;
}
else {
// When the first space after the characters
// (from the last) is encountered, return the
// length of the last word
if (char_flag == true)
return len;
}
}
return len;
}
}