题目:
分析:
两个思路,第一个是根据空格切割字符串,然后找最后一个。第二个思路是在原有字符串基础上从最后开始向前遍历,找到非空格后再往前遍历找到空格。
代码1:
class Solution {
public int lengthOfLastWord(String s) {
String[] a=s.split(" ");
return a[a.length-1].length();
}
}
代码2:
class Solution {
public int lengthOfLastWord(String s) {
int i=0;
int n=s.length()-1;
while(n>=0&&s.charAt(n)==' '){
n--;
}
while(n>=0&&s.charAt(n)!=' '){
i++;
n--;
}
return i;
}
}