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.

    指针相减

     1 class Solution {
     2 public:
     3     int lengthOfLastWord(const char *s) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         if (s == NULL)
     7             return 0;
     8             
     9         const char *start = s;
    10         int len = 0;
    11         while(*s != '\0')
    12         {
    13             if (*s == ' ')
    14             {
    15                 int l = s - start;                
    16                 if (l != 0)
    17                     len = l;
    18                 start = s + 1;
    19                 s++;
    20             }
    21             else
    22                 s++;
    23         }
    24         
    25         int l = s - start;
    26         if (l != 0)
    27             len = l;
    28             
    29         return len;
    30     }
    31 };

    模拟题,每次要记录的是空格前的字符开始索引,然后遇到空格得出单词长度。最后要注意的是,可能整个字符没有空格,或者最后一个不是空格,退出循环时要检测一下。

     1 class Solution {
     2 public:
     3     int lengthOfLastWord(const char *s) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         if (s == NULL)
     7             return 0;
     8             
     9         int start = -1;
    10         int index = 0;
    11         int len = 0;
    12         while(*s != '\0')
    13         {
    14            if (isalpha(*s) && start == -1)
    15                start = index;
    16                
    17            if (isspace(*s) && start != -1)
    18            {
    19                len = index - start;
    20                start = -1;
    21            }
    22            
    23            s++;
    24            index++;
    25         }
    26         
    27         if (start != -1)
    28             len = index - start;
    29         
    30         return len;
    31     }
    32 };
  • 相关阅读:
    ./是当前目录 ../是当前的上一级目录。上上级就是../../一般绝对路径时候常用
    java web 代码
    java特点
    KVC
    架构设计:前后端分离之Web前端架构设计
    从MVC到前后端分离
    you don't have permission 错误
    为什么Tomcat的webapps目录下新建的目录不能访问html文件?
    UTF-8编码规则(转)
    Delphi 有关的网址
  • 原文地址:https://www.cnblogs.com/chkkch/p/2765949.html
Copyright © 2011-2022 走看看