' '
, 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.
For example,
Given s =
"Hello World"
,return
5
.
public class Solution { public int lengthOfLastWord(String s) { // Remove leading and trailing spaces. String sCut = s.trim(); int n = sCut.length(); if (n == 0) return 0; int count = 0; // Length of last word for (int i = n-1; i >= 0; i--) if (sCut.charAt(i) != ' ') count++; else break; return count; } }
No comments:
Post a Comment