Problem 58

Length of Last Word

Posted by Ruizhi Ma on July 28, 2019

问题描述

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) {
        //corner case
        if(s == null || s.length() == 0 || s == " ") return 0;
        
        int count = 0, ans = 0;
        for(int i = 0; i < s.length(); i++){
            if(s.charAt(i) == ' '){
                count = 0;
            }else{
                count++;
                ans = count;
            }
        }
        
        return ans;
    }
}

复杂度分析

时间复杂度:O(n) 空间复杂度:O(1)