leetcode58. Length of Last Word

来源:互联网 发布:淘宝店铺信誉度怎么刷 编辑:程序博客网 时间:2024/06/06 19:32

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.

解法一

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

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;    }}

解法二

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

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;    }}