| 
 | 
 
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册  
 
x
 
- Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
 
  
- If the last word does not exist, return 0.
 
  
- Note: A word is defined as a character sequence consists of non-space characters only.
 
  
- Example:
 
  
- Input: "Hello World"
 
 - Output: 5
 
  复制代码 
- class Solution {
 
 -     public int lengthOfLastWord(String s) {
 
 -         
 
 -         s = s.replaceAll(" +"," ");
 
 -         
 
 -         if(s.equals(" ")){
 
 -             
 
 -             return 0;
 
 -         }
 
 -         
 
 -         String[] result = s.split(" ");
 
 -         
 
 -         return result[result.length-1].length();
 
 -         
 
 -     }
 
 - }
 
  复制代码 
 
 
 
 
利用split方法,效率有点低,继续改进。 
 
- class Solution {
 
 -     public int lengthOfLastWord(String s) {
 
 -         
 
 -         s = s.trim();
 
 -         
 
 -         return s.length() - (s.lastIndexOf(" ") +1) ;
 
 -     }
 
 - }
 
 
  复制代码 
 
 
 |   
 
 
 
 |