LeetCode – Length of Last Word (Java)
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.
Java Solution
We can scan the string from the end. When there is a letter, start counting the number of letters. This should handle cases like " a ".
public int lengthOfLastWord(String s) { if(s==null || s.length() == 0) return 0; int result = 0; int len = s.length(); boolean flag = false; for(int i=len-1; i>=0; i--){ char c = s.charAt(i); if((c>='a' && c<='z') || (c>='A' && c<='Z')){ flag = true; result++; }else{ if(flag) return result; } } return result; } |
<pre><code> String foo = "bar"; </code></pre>
-
Alik Elzin
-
David Moseby
-
ryanlr
-
David Moseby
-
neha patwardhan
-
CG
-
Eugene Arnatovich
-
James
-
NB****
-
Vimukthi Weerasiri
-
Ecch IOni
-
jensiepoo