leetcode -- Length of Last Word
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 = "Hello World"
,
return 5
.
[解题思路]
从最后往前扫描。处理如下三种模式:(*表示若干个空格)
1. "*"
2. "*word"
3. "*word*"
4. "word*"
1 public int lengthOfLastWord(String s) { 2 // Start typing your Java solution below 3 // DO NOT write main() function 4 if(s.length() == 0) 5 return 0; 6 7 String[] strs = s.split(" "); 8 for(int i = strs.length - 1; i >= 0; i++){ 9 if(isWord(strs[i])){ 10 return strs[i].length(); 11 } 12 } 13 return 0; 14 } 15 16 public boolean isWord(String s){ 17 if(s.length() == 0) 18 return false; 19 20 for(int i = 0; i < s.length(); i++){ 21 if((s.charAt(i) < 'a' && s.charAt(i) > 'z') || 22 (s.charAt(i) < 'A' && s.charAt(i) > 'Z')){ 23 return false; 24 } 25 } 26 27 return true; 28 } 29 }