首页 > 其他 > 详细

Length of Last Word

时间:2015-03-11 21:10:16      阅读:141      评论:0      收藏:0      [点我收藏+]

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.

思路:

  string的API操作

我的代码:

技术分享
public class Solution {
    public int lengthOfLastWord(String s) {
        if(s == null)   return 0;
        s = s.trim();
        if(s.length() == 0)   return 0;
        String[] words = s.split(" ");
        int len = words.length;
        return words[len-1].length();
    }
}
View Code

他人代码:

技术分享
public class Solution {
    public 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 (chars[i] == ‘ ‘) {
                    break;
                } else {
                    length++;
                }
            }
        }

        return length;
    }
}
View Code

学习之处:

  • 我的代码虽然简洁,但是由于调用了大量的API,会消耗掉好多时间
  • 他人的代码是从基本的做起,里面Length==0很精妙,成为了第一次访问的标志

Length of Last Word

原文:http://www.cnblogs.com/sunshisonghit/p/4330777.html

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