58. 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.
题意是找出一个字符串最后一个单词,字符串中每个单词用空格隔开。
这道题的坑:1、字符串中可能没有空格;2、字符串中全是空格;3、字符串末尾或开始是空格

1、自己做的时候没有想到trim或者lastIndexOf这些方法,思路是两个变量tmp和cnt,tmp记录当前单词的长度,cnt记录最后一个单词长度。碰到的不是空格tmp++,如果是空格并且tmp大于0,则把cnt更新为tmp,tmp再置0。如果最后一个字符不是空格,需要再判断一次tmp。

public int lengthOfLastWord1(String s) {
    if (s == null || s.length() == 0) {
        return 0;
    }

    int tmp = 0, res = 0;
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == ' ') {
            if (tmp > 0) {
                res = tmp;
            }
            tmp = 0;
        } else {
            tmp++;
        }
    }
    if (tmp != 0) {
        res = tmp;
    }

    return res;
}

2、应用trim的方法,trim会把字符串前后的空格去掉,因此我们从最后一个字符向前找,遇到空格或者找到第一个字符停止,计数结果就是最后一个单词长度。

public int lengthOfLastWord2(String s) {
    if (s == null || s.length() == 0) {
        return 0;
    }

    s = s.trim();
    int cnt = 0;
    for (int i = s.length() - 1; i >= 0; i--) {
        if (sTrim.charAt(i) != ' ') {
            cnt++;
        } else {
            break;
        }
    }

    return cnt;
}

3、lastIndexOf方法可以直接找到最后一个空格的索引位置k,所以trim以后,用字符串长度减去k再加1就是结果(lastIndexOf返回的索引从0开始,所以需要再加1)。

public int lengthOfLastWord(String s) {
    s = s.trim();
    int lastIndex = s.lastIndexOf(' ') + 1;
    return s.length() - lastIndex;        
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容