力扣-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函数进行求解个数,因为会把后边空格也计算上。

相关推荐
想吃火锅100515 小时前
【leetcode】200. 岛屿数量
算法·leetcode·职场和发展
Nil20816 小时前
leetcode 54螺旋矩阵
算法·leetcode·矩阵
evans在进步21 小时前
LeetCode 394:字符串解码——Java 单栈模拟与嵌套解析详解
java·python·leetcode
Nil20821 小时前
leetcode 189轮转数组
数据结构·算法·leetcode
吃着火锅x唱着歌1 天前
LeetCode 3885.设计事件管理器
算法·leetcode·职场和发展
土司大王1 天前
LeetCode hto100——字母异位词分组
java·算法·leetcode
土司大王1 天前
LeetCode hot100——两数之和
数据结构·算法·leetcode
.道阻且长.1 天前
7.LeetCode算法习题讲解--双指针--四数之和
算法·leetcode·职场和发展
Navigator_Z1 天前
LeetCode //C - 1200. Minimum Absolute Difference
c语言·算法·leetcode
wabs6661 天前
关于字符串【力扣344.反转字符串的思考】
数据结构·算法·leetcode