首页 > 其他 > 详细

leetcode之Length of Last Word

时间:2015-05-15 13:30:21      阅读:318      评论:0      收藏:0      [点我收藏+]

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;
	}

  

leetcode之Length of Last Word

原文:http://www.cnblogs.com/gracyandjohn/p/4505554.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!