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;
}
相关推荐
Hcoco_me17 分钟前
大模型面试题5:矩阵(M*M)特征值分解的步骤
算法·机器学习·矩阵
望眼欲穿的程序猿26 分钟前
Win系统Vscode+CoNan+Cmake实现调试与构建
c语言·c++·后端
非著名架构师1 小时前
极端天气下的供应链韧性:制造企业如何构建气象风险防御体系
大数据·人工智能·算法·制造·疾风气象大模型·风光功率预测
星轨初途1 小时前
数据结构排序算法详解(2)——选择排序(附动图)
c语言·数据结构·经验分享·笔记·b树·算法·排序算法
合作小小程序员小小店1 小时前
游戏开发,桌面%小游戏,俄罗斯方块%demo,基于vs2022,c语言,背景音乐,easyX,无数据库,
c语言·开发语言
kaikaile19952 小时前
基于 MATLAB 的室内三维定位
算法
AGI前沿2 小时前
AdamW的继任者?AdamHD让LLM训练提速15%,性能提升4.7%,显存再省30%
人工智能·算法·语言模型·aigc
Tan_Ying_Y2 小时前
什么是垃圾回收算法 他的底层原理是什么?
算法
EXtreme352 小时前
【C 语言专栏收官】预处理完全攻略:宏、条件编译与代码安全的最后一道防线
c语言·预处理·
Xの哲學3 小时前
Linux 分区表深度技术剖析
linux·网络·算法·架构·边缘计算