Skip to content

Latest commit

 

History

History
27 lines (22 loc) · 503 Bytes

Length of Last Word.md

File metadata and controls

27 lines (22 loc) · 503 Bytes

Solution

class Solution {
    public int lengthOfLastWord(String s) {
        if (s == null) {
            return 0;
        }
        s = s.trim();
        for (int i = s.length() - 1; i >= 0; i--) {
            if (s.charAt(i) == ' ') {
                return s.length() - 1 - i;
            }
        }
        return s.length();
    }
}

Time/Space Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(n)

Links