从后往前遍历,思路简单。但要注意极限情况下的数组越界问题。
class Solution {
public int lengthOfLastWord(String s) {
int i = s.length() - 1 ;
int ans = 0 ;
while(i >= 0 && s.charAt(i)==' '){
i-- ;
}
while(i >= 0 &&s.charAt(i)!=' '){//注意此行应该是i>=0在前,否则会引起数组越界
ans++;
i--;
}
return ans ;
}
}