[LeetCode] Length of last word

来源:互联网 发布:狗狗 知乎 编辑:程序博客网 时间:2024/05/29 13:10

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.

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.

这是一道实现题,从后往前扫描,如何判断最后一个word,有以下几种情况

1.“word   ”

2. "       "

3. "word"

4."  word  "

int lengthOfLastWord(const char *s) {    int length = strlen(s);    int count = 0;    for(int i= length-1; i>=0;i--){        if(s[i] == ' '){            if(count == 0) continue;            else return count;        }        count++;    }    return count;}

Java解法:

利用split()函数,通过空格“ ”将原字符串分组

public int lengthOfLastWord(String s) {        String [] splitStrings = s.split(" ");        for(int i=splitStrings.length-1;i>=0;i--){        if(splitStrings[i].length()>0)        return splitStrings[i].length();        }        return 0;    }


  • public String[] split(String regex)
    Splits this string around matches of the given regular expression.

    This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

    The string "boo:and:foo", for example, yields the following results with these expressions:

    RegexResult:{ "boo", "and", "foo" }o{ "b", "", ":and:f" }
    Parameters:
    regex - the delimiting regular expression
    Returns:
    the array of strings computed by splitting this string around matches of the given regular expression
    Throws:
    PatternSyntaxException - if the regular expression's syntax is invalid

0 0
原创粉丝点击