Seawolf 发表于 2019-8-20 06:24:19

leetcode 58. Length of Last Word

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.length();
      
    }
}



利用split方法,效率有点低,继续改进。

class Solution {
    public int lengthOfLastWord(String s) {
      
      s = s.trim();
      
      return s.length() - (s.lastIndexOf(" ") +1) ;
    }
}


页: [1]
查看完整版本: leetcode 58. Length of Last Word