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; }
相关文章推荐
- MyBatis 知识总结(一)
- 论文笔记|Fast R-CNN
- CSS外边距合并
- 冒泡排序(c语言实现)
- jsTree搜索排序向上向下
- 论文笔记|Spatial Pyramid Pooling in Deep Convolutional Networks for Visual Recognition
- 两种数据传输的方式-get/post
- 【codevs】1503 愚蠢的宠物
- java安装过程易出现问题(jdk,jre)
- I2C协议->裸机程序->adapter驱动程序分析
- iOS打包ipa步骤
- 论文笔记|Rich feature hierarchies for accurate object detection and semantic segmentation
- 10-1文字排版--字体、字号、颜色、粗体、斜体、下划线、删除线
- Fragment跳转时传递参数及结果回传的方法
- ORM原型概念
- 浅析 ThreadLocal
- caffe 实例笔记 4 Multilabel classification on PASCAL using python data-layers
- n个数里找出前m个数(或者 从10亿个浮点数中找出最大的1万个)
- Caffe 实例笔记 3 Brewing Logistic Regression then Going Deeper
- 本周学习进度