Length of Last Word

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很精妙,成为了第一次访问的标志

posted on 2015-03-11 19:39  zhouzhou0615  阅读(172)  评论(0编辑  收藏  举报

导航