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;
}
相关推荐
8Qi83 小时前
LeetCode 75:颜色分类(荷兰国旗问题)—— Java 题解 ✅
java·算法·leetcode·指针·排序
888CC++5 小时前
如何在 C 语言中进行程序调试?
前端·javascript·算法
(●—●)橘子……6 小时前
力扣第503场周赛练习理解
python·学习·算法·leetcode·职场和发展·周赛
明志数科8 小时前
4D时序标注技术详解:让机器人理解连续动作的数据基础
java·算法·机器人
KaMeidebaby8 小时前
卡梅德生物技术快报|原核表达系统工艺优化:包涵体重折叠 + 分子筛纯化实现功能 RBD 高效制备,附全参数配置
前端·人工智能·算法·数据挖掘·数据分析
无限码力9 小时前
携程0510笔试真题【单数组交换】
算法·携程笔试·携程笔试真题·携程0510笔试真题
zlinear数据采集卡9 小时前
基准电压电路深度解析:从理论参数到ZLinear采集卡的精准参考实战
c语言·单片机·嵌入式硬件·fpga开发·自动化
BlockWay9 小时前
WEEX Labs 周度观察:微软-OpenAI 合作调整与AI 多云趋势
大数据·人工智能·算法·安全·microsoft
风筝在晴天搁浅9 小时前
快手 CodeTop LeetCode 224.基本计算器
数据结构·算法·leetcode