首页 > 代码库 > [LeetCode] Length of Last Word

[LeetCode] Length of Last Word

今天又舔着脸开始LeetCode的征程了,本来是写在CSDN的,无奈遇上他家博客老是在升级中。。。

题目:

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.

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

For example,
Given s = "Hello World",
return 5.

Tag:

char, how to loop over char: how to tell the end, how to access, how to get next

体会:

代码基本是来源于看的别的大牛写的代码。我觉得这里主要是用了两个指针的那种思想,就是让一个人先走去探路,发现是‘ ’ 了,然后就变成0,为接下来遇到的新词要准备;如果遇到的不是‘ ’ ,那就是还是原先的那个词,那么就继续词长加1。然后再根据这个指针的情况去调整后面的那个指针,如果前面指针变成0了,说明这个词结束,那后面指针现在的长度就是当前最后一个词的长度了,留住它,如果前面之前没有变成0,说明词的长度还在增加,那么这个指针也跟着更新长度。

 

 1 class Solution { 2     public: 3          int lengthOfLastWord(const char *s) { 4             int count = 0; 5             int size = 0; 6             while ( *s != \0 ) { 7                 // if it is ‘ ‘ , then reset count, else count++ 8                 count = ( *s ==   ) ? 0 : (count + 1); 9                 // if count == 0, meet ‘ ‘, keep last, else update last10                 size = (count > 0) ? count : size;11                 s++;12             }13             return size;14         }15 };

 

Variant:

我觉得这个题的变形可以有这么几种,求char中最长的那个长度,求最短的那个的长度。比如求这个最长的

class Solution {    public:         int lengthOfLongestWord(const char *s) {            int count = 0;            int last = 0;            int longest = 0;            while ( *s != \0 ) {                // if it is ‘ ‘ , then reset count, else count++                count = ( *s ==   ) ? 0 : (count + 1);                // if count == 0, meet ‘ ‘, keep last, else update last                last = (count > 0) ? count : last;                longest = (longest < last) ? last : longest;                s++;            }            return longest;        }};

 Variant 2:

还有一种可能的变形就是,另外给定一个长度,求出其中长度等于这个给定长度的个数,也很类似的

[LeetCode] Length of Last Word