Length of Last Word

来源:互联网 发布:命令行进入linux mysql 编辑:程序博客网 时间:2024/05/01 03:05

Solution 1

public class Solution {    public int lengthOfLastWord(String s){        s = s.trim();//eliminate space characters in the head and tail        if(s == null || s.length() == 0)            return 0;        for(int i = 0; i < s.length(); i++){            if(s.charAt(s.length()-1-i) == ' ')                return i;            if(i == s.length()-1)                return i+1;        }        return -1;    }

Solution 2

public int lengthOfLastWord(String s){              return s.trim().length() > 0 ? s.split("\\s+")[s.split("\\s+").length - 1].length() : 0;    }
0 0