Question: a string containing only uppercase and lowercase letters and spaces. Returns the length of the last word. "ABC a" is 1 "ABC" is 3
There are two ideas: one from the beginning and the other from the back.
1. Remember the length of a word before the space from the beginning to the end. If there is a space to the end, output the record value. If there is a word after the space, count it again. Use flag to record whether spaces are encountered.
class Solution {public: int lengthOfLastWord(const char *s) { int flag = 0, cnt = 0; while(*s != ‘\0‘) { if (flag) {cnt = 0; flag = 0;} while (*s != ‘\0‘ && *s != ‘ ‘) {cnt++;s++;} while (*s != ‘\0‘ && *s == ‘ ‘) {s++;flag = 1;} } return cnt; }};
2. From the back to the front, first determine the last pointer, and then return the result after hitting the space after the first word.
class Solution {public: int lengthOfLastWord(const char *s) { const char *p = s + strlen(s) - 1; int cnt = strlen(s), t = 0; while(cnt > 0) { if (*p == ‘ ‘) {p--; cnt--;continue;} if (cnt > 0 && *p != ‘ ‘) { while(cnt > 0 && *p != ‘ ‘) { t++;cnt--;p--; } return t; } } return 0; }};
Leetcode length of last word