• leetcode 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 (last word means the last appearing word if we loop from left to right) in the string.

    If the last word does not exist, return 0.

    Note: A word is defined as a maximal substring consisting of non-space characters only.

    Example:

    Input: "Hello World"
    Output: 5

    题目难度:简单题

    解法一:从前往后扫描。

     1 int lengthOfLastWord(string s) {
     2         int cnt = 0;
     3         int curr = 0; //用于记录当前字符串的长度
     4         for (int i = 0; i < s.length(); ++i) {
     5             if (s[i] == ' ') {
     6                 if (curr != 0) {
     7                     cnt = curr;
     8                 }
     9                 curr = 0;
    10             } else {
    11                 ++curr;
    12             }
    13         }
    14         if ((s.length() > 0) && (s[s.length() - 1] != ' ')) { //如果最后一个字符不是空格,那么替换成最后字符串的长度
    15             cnt = curr;
    16         }
    17         return cnt;
    18     }

    解法二:从后往前扫描

     1 int lengthOfLastWord(string s) {
     2         int cnt = 0;
     3         int index = s.length() - 1;
     4         while (index >= 0 && (s[index] == ' ')) index--;
     5         while (index >= 0 && s[index] != ' ') {
     6             --index;
     7             cnt++;
     8         }
     9         return cnt;
    10     }
  • 相关阅读:
    Django的templates(模板)
    Django的urls(路由)
    Markdown中实现折叠代码块
    图片上传2
    Comparator 排序
    Serializable 序列化为文件
    统计连续签到的方法
    Serializable 序列化为字符串 base64
    Serializable 序列化使用限制
    Serializable 剔除某些不想保存的字段 transient
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/13681566.html
Copyright © 2020-2023  润新知