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.

这道题整体很简单

刚开始这道题想的太简单了,首先最开始的想法是得知s的长度,然后从头开始遍历找到最后一个空格的位置,作减法就可以得到最后单词的长度

然而忽略了,如果这个字符串结尾有空格的情况。如“a    ”

于是改变思路,从后面开始遍历,找到最后一个单词的最后一个字符开始计数,然后依次向前知道遇到第一个空格。

 

下面附上代码:

public static int lengthOfLastWord(String s) {

		int length = 0;
		char[] chars = s.toCharArray();
		for (int i = s.length() - 1; i >= 0; i--) {
			if (length == 0) {
				if (chars[i] == ' ') {
					continue;
				} else {
					length++;
				}
			} else {
				if (s.charAt(i) == ' ') {
					break;
				} else {
					length++;
				}
			}
		}

		return length;
	}

  

posted @ 2015-05-15 11:51  niuer++  阅读(113)  评论(0编辑  收藏  举报