58 Length of Last Word


title: Length of Last Word
tags:
- length-of-last-word
- No.58
- simple
- finite-automata
- string


Problem

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.

Example:

Input: "Hello World"
Output: 5

Corner Cases

  • begin with " "
  • end with " "
  • empty string ""
  • single word "a"

Solutions

Finite Automata

Use finite automata to solve this problem. The transition table is:

state " " "\w"
0 1(l=0) 2(l++)
1 1(l=0) 2(l++)
2 1(l=0) 2(l++)

But this table cannot deal with strings ending with " ", thus we should adjust the ending index, like String.rstrip() in python and String.trim() in java.

The running time is O(n).

class Solution {
    public int lengthOfLastWord(String s) {
        if (s.equals("")) {return 0;}

        int[][] dfa = new int[3][2];
        for (int i=0; i<3; i++) {
            dfa[i][0] = 1;
            dfa[i][1] = 2;
        }

        String[] t = s.split("");
        int      e = t.length - 1;
        while (t[e].equals(" ")) {
            e--;
            if (e < 0) {break;}
        }

        int l = 0;
        int j = 0;
        for (int i=0; i<=e; i++) {
            j = dfa[j][f(t[i])];
            l = (j == 2) ? l + 1 : 0;
        }
        return l;
    }

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

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,486评论 0 10
  • 真的不知道如何表达我的感谢!谢谢宇宙!谢谢刺猬!谢谢男闺蜜! 今天本来想写关于见男闺蜜的舒缓呢,结果还没写完情...
    猫公主喵阅读 146评论 0 0
  • 六年前的今天,我失去了你。 倏然、永远地失去是一种怎样的体验?我无数次提笔想描述我的创痛、缺失和那些...
    三叶草七月雨阅读 323评论 0 0
  • 对于不喝牛奶又想喝咖啡的人,espresso太苦,Americano 太淡(low),pour over是最佳选择...
    咪咖啡阅读 5,140评论 0 0