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;
}
相关推荐
饮水桶_T8 小时前
Git笔记
开发语言·笔记·算法
指掀涛澜天下惊8 小时前
强化学习进阶篇十四 DPO算法
深度学习·算法·机器学习·sft·预训练·dpo
AAA修煤气灶刘哥10 小时前
我都切到下一张图了,Agent 怎么还在解释上一张?
人工智能·算法·架构
Navigator_Z10 小时前
LeetCode //C - 1320. Minimum Distance to Type a Word Using Two Fingers
c语言·算法·leetcode
发疯的技术鼠10 小时前
第21篇-联合和枚举
c语言
青少儿编程课堂12 小时前
蓝桥杯青少组图形化真题:校园无人机编队灯光秀解析(全国青少年信息素养大赛·电子学会12月图形化考级同源考点)
c++·python·算法·bfs·信息学竞赛
Shadow(⊙o⊙)12 小时前
专题六:模拟算法
算法
23图1 天前
C 语言开散列表(拉链法)拆解:链挂得没错,key=-1 会去读 T[-1]
c语言·开发语言·散列表
小飞在努力1 天前
【实现负载均匀在线判题③】从零散模块到统一,编译运行全链路封装
c语言·开发语言·c++·笔记