58. Length of Last Word

第一遍C & C++

Posted by heroydx on March 6, 2018

题目分析

题目要计数一个字符串中最后一个单词的长度,如果不存在最后一个单词,则直接返回0。

Input: “Hello World”

Output: 5

要计数最后一个单词,比较简便的方法就是从后往前去读字符串,当第一次读到非空格的字符时记为1,以后依次加1,直到读到空格停止计数。然后返回结果。

编程实现

C实现

int lengthOfLastWord(char* s) {
  int lastLen = 0;
  char* p = s + strlen(s) -1;
  while(p>=s && isspace(*p)) p--;
  while(p>=s && !isspace(*(p--))) lastLen++;
  return lastLen;
}

C++实现

class Solution {
public:
    int lengthOfLastWord(string s) { 
        int len = 0, tail = s.length() - 1;
        while (tail >= 0 && s[tail] == ' ') tail--;
        while (tail >= 0 && s[tail] != ' ') {
            len++;
            tail--;
        }
        return len;
    }
};

总结反思

这道题主要用考察了遍历字符串的方法。C语言中用指针,C++中用s[index]