leetcode 58 求一个包含空格的字符串中最后一个字符串的长度
2016-02-18 10:50
429 查看
方法一:倒着找空格,并计算空格出现的个数。
class Solution { public: int lengthOfLastWord(string s) { int len = s.length(), index = -1, lastposition = len-1,cnt=0; string sep = " "; while(lastposition!=-1&&-1!=(index=s.find_last_of(sep,lastposition))){ if(index==lastposition){ lastposition--; cnt++; } else{ return len-index-1-cnt; } } if(lastposition==-1){ return 0; } return len-cnt; } };
方法二:顺着找,并及时擦除前面的字符串。
<pre name="code" class="cpp">class Solution { public: int lengthOfLastWord(string s) { int len=0; int pos; while (s.length()!=0){ pos = s.find(" "); if (pos==string::npos) return s.length(); else{ if (pos!=0) len = pos; s.erase(0,pos+1); } } return len; } };
相关文章推荐
- PhoneGap开发环境搭建
- java读写properties配置文件
- 部署基于国际版Azure的SharePoint三层架构服务器场
- Ubuntu Git服务器搭建
- Entity Framework Code first
- Web中的图标
- jQuery html表格排序插件:tablesorter
- Android studio 各种快捷键,使用技巧
- 用JavaScript将数字转换为大写金额
- Java Version Mismatch 解决方法
- nginx负载均衡的session共享问题的解决方法
- jenkins 的dns 异常导致日志撑爆服务器
- Linux网络编程 -- socketpair的使用
- eclipse调优
- 随想 2016-2-18 手机游戏
- Okhttp设置http缓存,在没有网络的情况下加载http缓存里面的内容
- intanceof/isInstance/isAssignableFrom区别
- Linux下面批量删除某种类型的文件
- 虚拟机VMware无法识别USB设备(USB摄像头)问题及解决方法
- Python之enumerate