题目:
Given a string s consists of upper/lower-case alphabets and empty space characters ' '
, return the length of last word in the string.
给定字符串s由大写/小写字母和空格字符''组成,返回字符串中最后一个单词的长度。(注意:很多个空格啊,不是每个单词一个空格)
If the last word does not exist, return 0.
如果最后一个单词不存在,则返回0。
Note: A word is defined as a character sequence consists of non-space characters only.
注意:单词定义为字符序列仅由非空格字符组成。
Example:
Input: "Hello World" Output: 5
解答:
方法一:
1 class Solution { 2 public int lengthOfLastWord(String s) { 3 int right=s.length()-1,res=0; //right指针指向s的末尾 4 while(right>=0 && s.charAt(right)==' ') //若字符串末尾为0,就不断将指针前移,直到指向最后一个单词的最后一个字符 5 right--; 6 while(right>=0 && s.charAt(right)!=' '){ //字符串最后一个单词的第一个字母前面一定是' ' 7 right--; 8 res++; 9 } 10 return res; 11 } 12 }
方法二:
class Solution { public int lengthOfLastWord(String s) { s=s.trim(); //trim() 方法用于删除字符串的头尾空白符 int lastWordIndex=s.lastIndexOf(' ')+1; return s.length()-lastWordIndex; } }