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.
For example,
Given s =
return
Given s =
"Hello World"
,return
5
.Solution:
Method 1: use split()
Use split() to remove spaces.
We check if last element is "".
If not, it should be a word. We safely return its length.
Code:
public class Solution { public int lengthOfLastWord(String s) { if (s == null || s.length() == 0) { return 0; } int end = s.length() - 1; int len = 0; while (end >= 0 && s.charAt(end) == ' ') { end--; } while (end >= 0 && s.charAt(end) != ' ') { end--; len++; } return len; } }
Method 2: Pointer
Use a point from the end of the string and go backward.
Go back till its not a space, or to the start of the word.
From this point, go back till it's a space, or to the start of the word.
The distance between the above two points is the length of the word.
Code:
public class Solution { public int lengthOfLastWord(String s) { String[] strs = s.split(" "); for (int i = strs.length - 1; i >= 0; i--) { if (strs[i].equals("")) { continue; } return strs[i].length(); } return 0; } }