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;
}
相关推荐
小南家的青蛙5 分钟前
LeetCode LCR 085 括号生成
算法·leetcode·职场和发展
jackzhuoa11 分钟前
Rust 异步核心机制剖析:从 Poll 到状态机的底层演化
服务器·前端·算法
夜晚中的人海12 分钟前
【C++】模拟算法习题
c++·算法·哈希算法
花月C17 分钟前
算法 - 差分
人工智能·算法·机器学习
拆房老料17 分钟前
深入解析提示语言模型校准:从理论算法到任务导向实践
人工智能·算法·语言模型
晨非辰35 分钟前
《数据结构风云》递归算法:二叉树遍历的精髓实现
c语言·数据结构·c++·人工智能·算法·leetcode·面试
Dream it possible!40 分钟前
LeetCode 面试经典 150_链表_LRU 缓存(66_146_C++_中等)(哈希表 + 双向链表)
c++·leetcode·链表·面试
_dindong3 小时前
牛客101:二叉树
数据结构·c++·笔记·学习·算法
数字化脑洞实验室4 小时前
如何理解不同行业AI决策系统的功能差异?
大数据·人工智能·算法
人邮异步社区4 小时前
推荐几本学习计算机语言的书
java·c语言·c++·python·学习·golang