当前位置:网站首页>LeetCode 58. Length of the last word

LeetCode 58. Length of the last word

2022-07-04 15:13:00 TianChao lobster

LeetCode 58. Length of last word

Topic link : https://leetcode.cn/problems/length-of-last-word/

Give you a string s, It consists of several words , Words are separated by some space characters . Return string the last one The length of the word .

word It's just letters 、 The largest substring that does not contain any space characters .

Example 1:

Input :s = “Hello World”
Output :5
explain : The last word is “World”, The length is 5.

Problem solving :

class Solution {
    
public:
    int lengthOfLastWord(string s) {
    
        if(s.empty())  return 0;

        const int size = s.size();
        int count{
    };
        for (size_t i=size; i>0; --i){
    
            //  Minus one means to remove the last character of the string .
            if(s[i-1] == ' '){
    
                if(count > 0) break;
                count = 0;
            }else{
    
                count ++;
            }
        }
        return count;
    }
};

Topic notes :

Reverse traversal , Cumulative length . But it should be noted that there is a hidden character at the end of the string , Therefore need -1. The essence '\0’ Is the end of string flag , Not included in string length , But take up memory space . Here and in a binary picture , Finding a row of consecutive pixels is similar . That is, traverse a row of pixels , How many consecutive pixels are satisfied , Returns the start pixel , End pixel , There are corresponding lines .

原网站

版权声明
本文为[TianChao lobster]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207041400439012.html