Java, low level, easy understand code


  • 0
    D
    public class Solution {
        public int lengthOfLastWord(String s)
        {
            int count = 0;  // used to record the length of word
            
            // scan from end to head
            for (int i = s.length() - 1; i >= 0; i--)
            {
                // if current char is not ' ', increase count
                if (s.charAt(i) != ' ') count++;
                else
                {
                    // if count != 0, that means we have already find the last word
                    if (count != 0) return count;
                }
            }
            
            return count;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.