[LeetCode 解题报告]058. Length of Last Word

 
 

Description:

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.

Example:

Input: "Hello World"
Output: 5

解题思路:

题意给定一个字符串,字符串由很多单词构成,每个单词之间用空格作为分隔符,要求返回最后一个单词的长度。


算法思路:

解法1. 先把字符串最后面的空格全部去掉,然后再返回最后一个单词的长度。


代码如下:

class Solution {
public:
    int lengthOfLastWord(string s) {
        
        int count = 0;
        int i = s.length() - 1, j;
        
        while(s[i] == ' ')
            i --;
        
        for (j = i; j >= 0; j --) {
            if(s[j] == ' ')
                break;
        }
        return i-j;
    }
};


解法2. 利用getline函数,以空格作为分隔符,直接读取一个个单词,不过注意:“ hello world ”这种case点,需要返回最后一个单词的长度。


代码如下:

class Solution {
public:
    int lengthOfLastWord(string s) {
        
        stringstream ss(s);
        string tmp;
        int length = 0;
        
        while(getline(ss, tmp, ' ')) {
            
            if (!tmp.empty()) {
                length = tmp.size();
            }
        }
        return length;
    }
};


猜你喜欢

转载自blog.csdn.net/caicaiatnbu/article/details/78647463