第9周 Length of Last Word

来源:互联网 发布:不用网络的麻将游戏 编辑:程序博客网 时间:2024/05/22 13:19

Length of Last Word

Leetcode algorithms problem 58: Length of Last Word

  • 问题描述

    Given a string s consists of upper/lower-case alphabets and empty space characters ’ ‘, return the length of last word in the string.
    If the last word does not exist, return 0.

  • 问题提示

    A word is defined as a character sequence consists of non-space characters only.

  • 思路

    1.一开始拿空字符来判断每个最后单词的长度,采取两个空格之间的长度作为输出,后面发现输入的字符串可以连续空字符,此法作罢
    2.遍历字符串,如果不是空字符,temp变量++,否则变为0,当temp长度不为0时,将值赋给sum

代码

class Solution {public:    int lengthOfLastWord(string s) {        int sum=0;        int temp=0;        for(int i = 0; i < s.length(); i++){            if(s[i] != ' '){                temp++;            }else{                temp = 0;            }            if(temp != 0){                sum = temp;            }        }        return sum;    }};};

时间复杂度: O(n)
空间复杂度: O(1)


原创粉丝点击