58. Length of Last Word【leetcode】

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.

public class Solution {
    public int lengthOfLastWord(String s) {
        int count=0;
        int len=s.length();
        char [] sc=s.toCharArray();
        for(int i=len-1;i>=0;i--){
            if(len==0){
                return 0;
            }
            else{
                if(sc[i]==' '){
                    if(count>0){
                        return count;    
                    }
                    else{
                        continue;
                    }
                    
                }
                else{
                    count++;
                }
            }
        }
        return count;
    }
}

解题思路:

首先这个题的意思是寻找一个字符串中最后一个词,就是说如果最后一个词的前后的空格都去除,取这个词的长度

特殊情况:空字符串,全是空字符,末尾有空字符+普通字符串四中情况

 

不积跬步无以至千里,千里之堤毁于蚁穴。 你是点滴积累成就你,你的丝丝懒惰毁掉你。 与诸君共勉
原文地址:https://www.cnblogs.com/haoHaoStudyShare/p/7341703.html