力扣58. 最后一个单词的长度

指针 + 反向遍历

  • 思路:
    • 用一个指针反向遍历字符串;
    • 用一个变量计数统计长度;
class Solution {
public:
    int lengthOfLastWord(string s) {
        int index = s.size() - 1;
        while (s[index] == ' ') {
            index--;
        }

        int length = 0;
        while (index >= 0 && s[index] != ' ') {
            length++;
            index--;
        }

        return length;
    }
};

你可能感兴趣的:(力扣实践,leetcode,算法,职场和发展)