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;
}
相关推荐
梵刹古音几秒前
【C语言】 字符数组与多维数组
c语言·数据结构·算法
咩咩不吃草9 分钟前
机器学习不平衡数据处理三招:k折交叉验证、下采样与过采样实战
人工智能·算法·机器学习·下采样·过采样·k折交叉验证
weixin_4521595510 分钟前
模板编译期条件分支
开发语言·c++·算法
多恩Stone10 分钟前
【3DV 进阶-11】Trellis.2 数据处理与训练流程图
人工智能·pytorch·python·算法·3d·aigc·流程图
老师用之于民12 分钟前
【DAY20】数据结构基础:(算法)排序、折半查找的函数实现
数据结构·算法·排序算法
时时三省12 分钟前
【时时三省】(C语言基础)共用体/联合体
c语言
一起养小猫15 分钟前
Flutter for OpenHarmony 进阶:推箱子游戏算法与关卡设计深度解析
算法·flutter·游戏
民乐团扒谱机16 分钟前
【微实验】Zhang-Suen 快速并行细化算法与MATLAB实现
人工智能·学习·算法·计算机视觉·数学建模·matlab
iAkuya18 分钟前
(leetcode)力扣100 60单词搜索(回溯)
算法·leetcode·职场和发展
卖报的大地主20 分钟前
强化学习在图像生成中的应用:范式演进、算法机制与前沿展望
算法