返回介绍

Length of Last Word

发布于 2025-02-22 13:01:22 字数 1680 浏览 0 评论 0 收藏 0

Source

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.

Have you met this question in a real interview? Yes
Example
Given s = "Hello World", return 5.

Note
A word is defined as a character sequence consists of non-space characters only.

题解 1

关键点在于确定最后一个字符串之前的空格,此外还需要考虑末尾空格这一特殊情况,故首先除掉右边的空白字符比较好。

Java

public class Solution {
  /**
   * @param s A string
   * @return the length of last word
   */
  public int lengthOfLastWord(String s) {
    if (s == null | s.isEmpty()) return 0;

    // trim right space
    int begin = 0, end = s.length();
    while (end > 0 && s.charAt(end - 1) == ' ') {
      end--;
    }
    // find the last space
    for (int i = 0; i < end; i++) {
      if (s.charAt(i) == ' ') {
        begin = i + 1;
      }
    }

    return end - begin;
  }
}

源码分析

两根指针。

复杂度分析

遍历一次,时间复杂度 O(n)O(n)O(n).

题解 2

直接从后向前扫描

C++

  int lengthOfLastWord(string s) {
    if (s.size() == 0) return 0;

    int count = 0;
    for (int i=s.size()-1; i>=0; i--)
      if (s[i] == ' ') {
        if (count) break;
      } else count++;

    return count;
  }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文