Tried it with spliting words method. But need to check empty situation.
1 class Solution { 2 public: 3 int lengthOfLastWord(const char *s) { 4 int len = strlen(s); 5 if (len == 0) return 0; 6 for (int i = len-1; i >= 0; i--) { 7 if (s[i] == ‘ ‘) { 8 len = i; 9 } else if (i == 0 || s[i-1] == ‘ ‘) { 10 return len - i; 11 } 12 } 13 } 14 };
This method uses a flag to record whether we have encountered real chars before.
1 class Solution { 2 public: 3 int lengthOfLastWord(const char *s) { 4 int len = strlen(s), result = 0; 5 bool flag = false; 6 for (int i = len-1; i >= 0; i--) { 7 if (s[i] == ‘ ‘) { 8 if (flag) return result; 9 } else { 10 flag = true; 11 result++; 12 } 13 } 14 return result; 15 } 16 };
时间: 2024-10-13 15:39:05