LeetCode //58. Length of Last Word

58. Length of Last Word

Given a string s consisting of words and spaces, return the length of the last word in the string.

A word is a maximal substring consisting of non-space characters only.

Example 1:

Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.

Example 2:

Input: num = 58s = " fly me to the moon "
Output: 4
Explanation: The last word is "moon" with length 4.

Example 3:

Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.

Constraints:

  • 1 < = s . l e n g t h < = 1 0 4 1 <= s.length <= 10^4 1<=s.length<=104
  • s consists of only English letters and spaces ' '.
  • There will be at least one word in s.

From: LeetCode

Link: 58. Length of Last Word


Solution:

Ideas:
First determine the length of the string, and then set the flag "sign" to judge the end of the word, and start to loop through the last digit of the string array, and skip it directly when the beginning is a space. Count when a character is encountered, and set the judgment flag "sign" to 1. When a space is encountered again and the judgment flag "sign" is 1, the word ends, jump out of the loop, and return the length "length".
Code:
c 复制代码
int lengthOfLastWord(char * s){
    int len = strlen(s);
    int sign = 0;
    int length = 0;
    for(int i = len - 1; i >= 0; i--){
        if(s[i] == ' ' && sign == 0){
            continue;
        }
        if(s[i] != ' '){
            sign = 1;
            length++;
        }
        else if(sign == 1){
            break;
        }
        
    }
    return length;
}
相关推荐
专注仿真42 分钟前
梯度提升类(XFBoost)算法详解与代码实例
开发语言·人工智能·python·算法·大模型训练·控制算法
小豆庄1 小时前
视频遮罩追踪退场后ID撞号的排查—多目标场景下的失效
opencv·算法·bug·视频·python3.11
Tisfy1 小时前
LeetCode 3882.网格图中最小异或路径:动态规划
算法·leetcode·动态规划
D e re k ZH2 小时前
P5025 [SNOI2017] 炸弹
c++·算法
A boy CDEF girl2 小时前
算法题专栏:优选算法
数据结构·算法·leetcode
没落之王2 小时前
三易五行看宋朝的三界确立
大数据·人工智能·算法
wuminyu3 小时前
Java字节码学习总结:字节码如何加载、解析和执行
java·linux·c语言·jvm·c++
坤坤子吖3 小时前
算法学习——单调队列
开发语言·c++·笔记·学习·算法
Js.Tx4 小时前
【具体数学 Concrete Mathematics】2.1.5 一般性的方法
算法·具体数学
秋天的怀念_David6 小时前
算法一千零一夜 · 作品相关:版权与致谢声明
程序人生·算法·学习方法