Title: The length of the last word


Given a string containing only uppercase and lowercase letters and Spaces, return the length of its last word. If the last word does not exist, return 0. Description: A word is a string of letters that does not contain any Spaces.Copy the code

Example:


Input: "Hello World" Output: 5Copy the code

Think about:


The length variable is used to record the length of the array, traversing the array from the back forward, if the character is not "" length+1, return length if the character is" ".Copy the code

Implementation:


class Solution { public int lengthOfLastWord(String s) { char[] c = s.toCharArray(); int length = 0; for(int i = c.length - 1; i >= 0; i--){ if (c[i] == ' ' && length ! = 0){ return length; } if (c[i]! =' '){ length++; } } return length; }}Copy the code