给出一个只包含大小写字母和空格的字符串s,请返回字符串中最后一个单词的长度
如果字符串中没有最后一个单词,则返回0
注意:单词的定义是仅由非空格字符组成的字符序列。
例如:
s ="Hello World",
返回5。
解法一:
class Solution {
public int lengthOfLastWord(String s) {
String[] array = s.trim().split("\\s+");
return array[array.length - 1].length();
}
}
解法二:
public int lengthOfLastWord(String s) {
if (s == null | s.isEmpty()) return 0;
int begin = 0, end = s.length();
while (end > 0 && s.charAt(end - 1) == ' ') {
end--;
}
for (int i = 0; i < end; i++) {
if (s.charAt(i) == ' ') {
begin = i + 1;
}
}
return end - begin;
}
解法三:
public int lengthOfLastWord(String s) {
int count = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == ' ') {
if (count > 0) {
break;
}
} else {
count++;
}
}
return count;
}