58.Length of Last Word
题目链接:https://leetcode.com/problems/length-of-last-word/description/
题目大意:给出一个字符串最后一个单词的长度。
法一:模拟,代码如下(耗时6ms):
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public int lengthOfLastWord(String s) { 2 int len = s.length(), cnt = 0; 3 boolean flag = false; 4 for(int i = len - 1; i >= 0; i--) { 5 if(s.charAt(i) == ' ') { 6 if(flag == true) { 7 break; 8 } 9 } 10 else { 11 //直接计数最后一个单词的字符个数 12 cnt++; 13 flag = true; 14 } 15 } 16 return cnt; 17 }
法二(借鉴):一行代码,利用java中的封装函数:trim(),length()。代码如下(耗时5ms):
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public int lengthOfLastWord(String s) { 2 return s.trim().length() - s.trim().lastIndexOf(' ') - 1; 3 }