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;
}
相关推荐
圣保罗的大教堂18 分钟前
leetcode 2799. 统计完全子数组的数目 中等
leetcode
SsummerC24 分钟前
【leetcode100】组合总和Ⅳ
数据结构·python·算法·leetcode·动态规划
YuCaiH1 小时前
数组理论基础
笔记·leetcode·c·数组
2301_807611491 小时前
77. 组合
c++·算法·leetcode·深度优先·回溯
YuforiaCode2 小时前
第十三届蓝桥杯 2022 C/C++组 修剪灌木
c语言·c++·蓝桥杯
SsummerC2 小时前
【leetcode100】零钱兑换Ⅱ
数据结构·python·算法·leetcode·动态规划
好易学·数据结构3 小时前
可视化图解算法:二叉树的最大深度(高度)
数据结构·算法·二叉树·最大高度·最大深度·二叉树高度·二叉树深度
程序员-King.3 小时前
day47—双指针-平方数之和(LeetCode-633)
算法·leetcode
阳洞洞3 小时前
leetcode 1035. Uncrossed Lines
算法·leetcode·动态规划·子序列问题
小鹿鹿啊4 小时前
C语言编程--15.四数之和
c语言·数据结构·算法