Java solution with comments


  • 0
    W
    //思路: 从后往前开始查找, 当出现非空格字符时开始计数
    public int lengthOfLastWord(String s) {
    	if (s == null || s.length() == 0)
    		return 0;
    	int length = 0;
    	int tail = s.length() - 1;
    	while (tail >= 0 && s.charAt(tail) == ' ') // 从后往前查找第一个非空格字符
    		tail--;
    	while (tail >= 0 && s.charAt(tail) != ' ') { // 从后往前统计非空格字符个数
    		length++; // 单词长度计数加1
    		tail--;
    	}
    	return length;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.