058.Length of Last Word Posted on 2017-09-13 | In LeetCode Test cases123456"""Hello World""OneWord""Space "" Space""b a " Solution 1: accepted 5msTime: O(n)Space: O(1) 1234567891011public int lengthOfLastWord(String s) { s = s.trim(); int len = s.length(); for(int i = len - 1; i >= 0; i--) { if (s.charAt(i) == ' ') { return len - i- 1; // return s.substring(i + 1, len).length(); // improved } } return len == 0? 0 : len;} Other solutions123public int lengthOfLastWord(String s) { return s.trim().length()-s.trim().lastIndexOf(" ")-1;} 12345678910111213141516public class Solution { public int lengthOfLastWord(String s) { String s1 = s.trim(); int count = 0; for(int i = s1.length() - 1; i >=0; i--){ if (s1.charAt(i) != ' '){ count ++; } else{ break; } } return count; }}