题目:
方法二:利用charAt()。
字符串包含大小写字母和' '空格,返回最后一个单词的长度。
For example,
Given s ="Hello World",
return5.
方法一:利用split函数。
public class Solution {
public int lengthOfLastWord(String s) {
if(s == null||s.trim().equals("")
return 0;
String []str=s.split(" ");
return str[str.length-1].length();
}
}
方法二:利用charAt()。
public class Solution {
public int lengthOfLastWord(String s) {
if(s == null||s.trim().isEmpty())
return 0;
s=s.trim();
int index=s.length()-1;
while(index>=0&&s.charAt(index)!=' ')
{
index--;
}
return s.length()-1-index;
}
}