zoukankan      html  css  js  c++  java
  • Leetcode | 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.

    这题是要求最后一个单词的长度。而且因为输入是一个char *,而不是已经长度的数组,所以从左往右扫。碰到空格就保留它的位置。碰到非空格就计算长度。如果前面没有空格,就直接和字符串开头相比较。如果有空格就和最近的空格比较。

    这种方法就可以忽略末尾是不是有空格,或者连续空格等情况了。

     1 class Solution {
     2 public:
     3     int lengthOfLastWord(const char *s) {
     4         const char *p = s, *space = NULL;
     5         int l = 0;
     6         for (; *p != ''; p++) {
     7             if (*p == ' ') {
     8                 space = p;
     9             } else if (space == NULL) {
    10                 l = p - s + 1;
    11             } else {
    12                 l = p - space;
    13             }
    14         }
    15         return l;
    16     }
    17 };
  • 相关阅读:
    选择器的使用总结
    突出展示
    京东轮播图的·实现方式
    jquery实现下拉菜单
    jquery实现淘宝动态图展示商品
    jquery查找子元素和兄弟元素
    调制解调
    同步异步串行并行
    Quartus ii 初学遇到的问题以及解决
    PLL
  • 原文地址:https://www.cnblogs.com/linyx/p/3734569.html
Copyright © 2011-2022 走看看