一.反向遍历
class Solution
{
public int lengthOfLastWord(String s)
{
int index = s.length() - 1;
while (s.charAt(index) == ' ') //s.charAt():返回指定索引处的字符
{
index--;
}
int wordLength = 0;
while (index >= 0 && s.charAt(index) != ' ')
{
wordLength++;
index--;
}
return wordLength;
}
}
二.API战士👨
class Solution
{
public int lengthOfLastWord(String s)
{
s = s.trim(); //trim():去掉字符串两端的多余的空格
return s.length() - s.lastIndexOf(" ") - 1;
//s.lastIndexOf(int ch):返回指定字符在此字符串中最后一次出现处的索引
}
}