[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",
return5.
https://oj.leetcode.com/problems/length-of-last-word/
思路:从后向前扫描,定位lastword然后记录其长度。
public class Solution { public int lengthOfLastWord(String s) { if (s == null || s.length() < 1) return 0; int n = s.length(); int i; int len = 0; boolean in = false; for (i = n - 1; i >= 0; i--) { if (!in && s.charAt(i) != ' ') { in = true; } if (in && s.charAt(i) != ' ') { len++; } if (in && s.charAt(i) == ' ') break; } return len; } public static void main(String[] args) { System.out.println(new Solution().lengthOfLastWord("Hello World")); System.out.println(new Solution().lengthOfLastWord("Hello World ")); System.out.println(new Solution().lengthOfLastWord("Hello a ")); System.out.println(new Solution().lengthOfLastWord("")); System.out.println(new Solution().lengthOfLastWord(" ")); } }
第二遍记录:
改了下代码,注意从后遍历时j>=0的越界判断不要忘记了。
public class Solution { public int lengthOfLastWord(String s) { if(s==null||s.length()==0) return 0; int n = s.length(); int j = n-1; while(j>=0&&s.charAt(j)==' ') j--; int len =0; while(j>=0&&s.charAt(j)!=' '){ len++; j--; } return len; } }