LeetCode-easy-Length of Last Word

Length of Last Word

这道题很简单,一般来说有两种方法
第一种就是用栈的思想,从头到尾扫描,遇到字母压栈,而遇到空格就将之前空格的全部出栈。当然出栈也有前提,就是后续必须还有元素,且非空格元素才可出栈。
第二种就是从尾部进行扫描,遇到第一个字母就加一,再直接进行统计,遇到下一个空格或者head就结束。
第一种使用cpp实现(莫得办法,准备复试,所以第二种使用c语言)

class Solution {
public:
    int lengthLastWord(std::string s) {
        std::vector<char> stack;
        int count = s.size();
        for (int i = 0; i < count; i++) {
            if (s[i] != ' ') stack.push_back(s[i]);
            else if(i<count-1&&s[i+1]!=' ')stack.clear();//If string hava adquate gredient,and this gredient don't  the  space,can clear stack.
}
        return stack.size();
    }

};//望看到的人心里面轻嘲这个英语

以下是c语言版本,写的比我的cpp还臭

int lengthOfLastWord(char * s) {
    int length = 0;
    while (*s != '\0') {
        length++;
        s++;
    }//above all circulation length and s add ex-one.
    int len = 0;
    --length;
    --s;//subtract the one
    while (length>=0&&*s== ' ') {
        length--;
        s--;
    }
    while (length>=0&&*s!=' ') { 
        length--;
        len++;
        s--;
    }
    return len;
}

猜你喜欢

转载自www.cnblogs.com/Yekko/p/12158735.html