力扣-58. 最后一个单词的长度

复制代码
int lengthOfLastWord(char* s) 
{
    char* temp = s;
    char* ret = s;

    int count = 0;/*返回的长度*/
    while (*temp)
    {
        /*只记录空格后是字母的地址*/
        if ((*temp == ' ') && (*(temp + 1) != '\0') && (*(temp + 1) != ' '))
        {
            ret = temp + 1;
        }
        temp++;
    }

    while (*ret)
    {
        if (isalpha(*ret) != 0)/*判断空格后的字符串中函数字符的个数*/
        {
            count++;
        }
        else
        {
            break;
        }
        ret++;
    }

    return count;
}

思路:

1.当空格后是字母时,记录首字母的地址。如果多个空格连续以及空格后边就是结束符'\0'的情况时,不要记录地址。

2.拿到记录的地址后,遍历地址后边的字符串,记录字母的个数。不要使用strlen函数进行求解个数,因为会把后边空格也计算上。

相关推荐
wenyq71 小时前
LeetCode 2904. Shortest and Lexicographically Smallest Beautiful String
算法·leetcode
_Narcissus_3 小时前
分治&递归
数据结构·c++·笔记·算法·leetcode·递归·分治
青 春 记 忆7 小时前
LeetCode 283. 移动零|Python 解法详解
python·算法·leetcode
evans在进步10 小时前
LeetCode 189 轮转数组:三次反转为什么能实现右旋?
数据结构·算法·leetcode
圣保罗的大教堂12 小时前
leetcode 3734. 大于目标字符串的最小字典序回文排列 困难
leetcode
土司大王20 小时前
LeetCode hot100——对称二叉树
算法·leetcode·职场和发展
Navigator_Z20 小时前
LeetCode //C - 1208. Get Equal Substrings Within Budget
c语言·算法·leetcode