码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode – Refresh – Length of Last Word

时间:2015-03-20 08:03:07      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

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 };

 

LeetCode – Refresh – Length of Last Word

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4352666.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!