即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

leetcode58. Length of Last Word

编程语言 rxt2012kc 14℃ 0评论
本文目录
[隐藏]

1.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.

2.解法一

先对字符串去除无用空格,然后倒序输出第一个空格之前的词。

public class Solution {
    public int lengthOfLastWord(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        char[] arr = s.toCharArray();
        int len = arr.length;
        String clean = clean(arr, len);
        char[] cleanArr = clean.toCharArray();
        if (cleanArr == null || cleanArr.length == 0) {
            return 0;
        }
        int cleanLen = cleanArr.length;
        int j = 0;
        for (int i = cleanLen - 1; i >= 0; i--) {
            if (cleanArr[i] != ' ') {
                j++;
            } else {
                break;
            }
        }

        return j;
    }
    public String clean(char[] arr, int len) {
        int i = 0, j = 0;
        while (j < len) {
            while (j < len && arr[j] == ' ') {
                j++;
            }
            while (j < len && arr[j] != ' ') {
                arr[i++] = arr[j++];
            }
            while (j < len && arr[j] == ' ') {
                j++;
            }
            if (j < len) {
                arr[i++] = ' ';
            }
        }
        String s = new String(arr).substring(0, i);
        return s;
    }
}

3.解法二

只针对最后一个词,最后一个词之后的空格过滤掉

public class Solution {
    public int lengthOfLastWord(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        char[] arr = s.toCharArray();
        int len = arr.length;
        int j = 0;
        for (int i = len - 1; i >= 0; i--) {
            while (i >= 0 && arr[i] == ' ') {
                i--;
            }
            while (i >=0 && arr[i] != ' ') {
                j++;
                i--;
            }
            break;
        }

        return j;
    }
}

转载请注明:CodingBlog » leetcode58. Length of Last Word

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情