2016.6.19——Length of Last Word

Length of Last Word

本题收获:

1.str.size()为负

2.size_t引发的死循环

3.题目思路,有时在写代码时很不清楚边界条件的输出值是什么,若为面试,一定要问清楚。

  题目:

  Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

  If the last word does not exist, return 0.

  Note: A word is defined as a character sequence consists of non-space characters only.

  For example,
  Given s = "Hello World",
  return 5.

  边界条件:

  1. " "  return 0

  2."a  "  return 1 (我开始错以为这种情况返回0 )

  思路:

    我的思路:直接找,for循环

    leetcode:直接找,while循环     

  正确代码:

 1 class Solution {
 2 public:
 3     int lengthOfLastWord(string s) { 
 4         int len = 0, tail = s.length() - 1;
 5         while (tail >= 0 && s[tail] == ' ') tail--;
 6         while (tail >= 0 && s[tail] != ' ') {
 7             len++;
 8             tail--;
 9         }
10         return len;
11     }
12 };

  我写的:

 1 class MyClass
 2 {
 3 public:
 4     int lengthOfLastWord(string str)
 5     {
 6         if (str.size() == 0) return 0;
 7         int n = str.size() - 1;
 8         int j = 0;
 9 
10     while (n >= 0 && str[n] == ' ')
11     {
12         n--;
13     }
14     while (n >= 0 && str[n] != ' ')
15     {
16         j++;
17         n--;
18     }
19     return j;
20     }
21 };

  出现死循环的代码:

  

 1 class MyClass
 2 {
 3 public:
 4     int lengthOfLastWord(string str)
 5     {        
 6         if (str.size() == 0) return 0;
 7         int j = 0;
 8         int n = str.size() - 1;
 9         for (size_t i = n; i >= 0; i--)        //从size_t换到 int就不会出现i = 4294967295
10         {
11             cout << i << endl;
12             if (str[n] == ' ') return 0;
13             else
14             {
15                 j++;
16                 continue;
17             }    
18 
19             if (str[i] == ' ') break;
20             else j++;
21         }
22         return j;
23     }
24 };

  因为size_t是unsigned int/unsigned long 型 ,好吧 具体我也不太清楚是怎么样的!

  测试全代码:

  

 1 #include "stdafx.h"
 2 #include "iostream"
 3 #include "string"
 4 using namespace std;
 5 
 6 class MyClass
 7 {
 8 public:
 9     int lengthOfLastWord(string str)
10     {
11         if (str.size() == 0) return 0;
12         int n = str.size() - 1;
13         int j = 0;
14 
15     while (n >= 0 && str[n] == ' ')
16     {
17         n--;
18     }
19     while (n >= 0 && str[n] != ' ')
20     {
21         j++;
22         n--;
23     }
24     return j;
25     }
26 };
27 
28 int _tmain(int argc, _TCHAR* argv[])
29 {
30     string str;
31     str = "a";
32     MyClass solution;
33     int m = 0;
34     m = solution.lengthOfLastWord(str);
35     cout << m << endl;
36     system("pause");
37     return 0;
38 }

 

posted on 2016-06-19 20:26  zhuzhu2016  阅读(145)  评论(0编辑  收藏  举报

导航