C#的实现:
public class Solution { public int LengthOfLastWord(string s) { s = s.Trim(); if (s.Length == 0 || s.Trim().Length == 0) { return 0; } var len = s.Length; var list = s.Split(' '); var word = list[list.Length - 1]; return word.Length; } }
https://leetcode.com/problems/length-of-last-word/#/description
补充Java的实现:
1 class Solution { 2 public int lengthOfLastWord(String s) { 3 s = s.trim(); 4 int n = s.length(); 5 if(n == 0){ 6 return 0; 7 } 8 String[] array = s.split(" "); 9 int len = array.length; 10 return array[len-1].length(); 11 } 12 }