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 = "Hello World",
return 5.
題意是找出一個(gè)字符串最后一個(gè)單詞,字符串中每個(gè)單詞用空格隔開。
這道題的坑:1、字符串中可能沒有空格;2、字符串中全是空格;3、字符串末尾或開始是空格
1、自己做的時(shí)候沒有想到trim或者lastIndexOf這些方法,思路是兩個(gè)變量tmp和cnt,tmp記錄當(dāng)前單詞的長度,cnt記錄最后一個(gè)單詞長度。碰到的不是空格tmp++,如果是空格并且tmp大于0,則把cnt更新為tmp,tmp再置0。如果最后一個(gè)字符不是空格,需要再判斷一次tmp。
public int lengthOfLastWord1(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int tmp = 0, res = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') {
if (tmp > 0) {
res = tmp;
}
tmp = 0;
} else {
tmp++;
}
}
if (tmp != 0) {
res = tmp;
}
return res;
}
2、應(yīng)用trim的方法,trim會(huì)把字符串前后的空格去掉,因此我們從最后一個(gè)字符向前找,遇到空格或者找到第一個(gè)字符停止,計(jì)數(shù)結(jié)果就是最后一個(gè)單詞長度。
public int lengthOfLastWord2(String s) {
if (s == null || s.length() == 0) {
return 0;
}
s = s.trim();
int cnt = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (sTrim.charAt(i) != ' ') {
cnt++;
} else {
break;
}
}
return cnt;
}
3、lastIndexOf方法可以直接找到最后一個(gè)空格的索引位置k,所以trim以后,用字符串長度減去k再加1就是結(jié)果(lastIndexOf返回的索引從0開始,所以需要再加1)。
public int lengthOfLastWord(String s) {
s = s.trim();
int lastIndex = s.lastIndexOf(' ') + 1;
return s.length() - lastIndex;
}