Given a string s consists of upper/lower-case alphabets and empty space characters
' ', return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
For example,
Given s =
return
Given s =
"Hello World",return
5.Hint: always remember to first eliminate all spaces after the last word!
Length of last word
01 public int lengthOfLastWord(String s) {
02 char []str=s.toCharArray();
03 if(str.length==0)
04 return 0;
05 int count=0;
06 int last=str.length-1;
07
08 //eliminate all space at the end
09 while(last>=0 && str[last]==' ')
10 {
11 last--;
12 }
13
14 while(last>=0 && str[last]!=' ')
15 {
16 count++;
17 last--;
18 }
19
20 return count;
21 }
02 char []str=s.toCharArray();
03 if(str.length==0)
04 return 0;
05 int count=0;
06 int last=str.length-1;
07
08 //eliminate all space at the end
09 while(last>=0 && str[last]==' ')
10 {
11 last--;
12 }
13
14 while(last>=0 && str[last]!=' ')
15 {
16 count++;
17 last--;
18 }
19
20 return count;
21 }
没有评论:
发表评论