您的位置:首页 > 其它

2016.6.19——Length of Last Word

2016-06-19 20:26 225 查看

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循环     

  正确代码:

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


  我写的:

class MyClass
{
public:
int lengthOfLastWord(string str)
{
if (str.size() == 0) return 0;
int n = str.size() - 1;
int j = 0;

while (n >= 0 && str
== ' ')
{
n--;
}
while (n >= 0 && str
!= ' ')
{
j++;
n--;
}
return j;
}
};


  出现死循环的代码:

  

class MyClass
{
public:
int lengthOfLastWord(string str)
{
if (str.size() == 0) return 0;
int j = 0;
int n = str.size() - 1;
for (size_t i = n; i >= 0; i--)        //从size_t换到 int就不会出现i = 4294967295
{
cout << i << endl;
if (str
== ' ') return 0;
else
{
j++;
continue;
}

if (str[i] == ' ') break;
else j++;
}
return j;
}
};


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

  测试全代码:

  

#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;

class MyClass
{
public:
int lengthOfLastWord(string str)
{
if (str.size() == 0) return 0;
int n = str.size() - 1;
int j = 0;

while (n >= 0 && str
== ' ')
{
n--;
}
while (n >= 0 && str
!= ' ')
{
j++;
n--;
}
return j;
}
};

int _tmain(int argc, _TCHAR* argv[])
{
string str;
str = "a";
MyClass solution;
int m = 0;
m = solution.lengthOfLastWord(str);
cout << m << endl;
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: