[leetcode 58] Length of Last Word
来源:互联网 发布:windows8装mac 编辑:程序博客网 时间:2024/06/06 02:08
Question:
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、如果S长度为0,直接返回0即可;
2、如果s全是“ ”,也是直接返回0;
3、如果s中没有“ ”,则直接返回s的长度即可;
4、如果s中有“ ”,则将s以“ ”分词,将最后一个词的长度返回即可。
<span style="font-size:14px;">class Solution {private: vector<string> split(string s, string pattern){ int pos; vector<string> result; s += pattern; for(int i = 0; i < s.size(); ++i){ pos = s.find(pattern,i); if(pos < s.size() && pos != i){ string sub = s.substr(i,pos-i); result.push_back(sub); i = pos + pattern.size()-1; } } return result; }public: int lengthOfLastWord(string s) { if(s.length() == 0) return 0; int i; for( i = 0; i < s.size(); i++){ if(s[i] != ' ') break; } if(i == s.size()) return 0; if(s.find(" ",0) != string::npos){ vector<string> st; st = split(s," "); return st[st.size()-1].length(); } else return s.length(); }};</span>
0 0
- [leetcode 58] Length of Last Word
- leetcode-58 Length of Last Word
- Leetcode NO.58 Length of Last Word
- LeetCode #58 length of Last Word
- [LeetCode 58]Length of Last Word
- leetcode || 58、Length of Last Word
- LeetCode 58 Length of Last Word
- [Leetcode 58, easy] Length of Last Word
- Length of Last Word (leetCode 58)
- leetcode[58]:Length of Last Word
- 【leetcode c++】58 Length of Last Word
- leetcode 58:Length of Last Word
- LeetCode---(58)Length of Last Word
- leetcode-58-Length of Last Word
- Leetcode# 58 Length of Last Word
- [leetcode-58]Length of Last Word(c)
- leetcode 58: Length of Last Word
- leetCode #58 Length of Last Word
- hdu 1297
- Qt中常见对话框的使用/QMessageBox/QFontDialog/QFileDialog
- java设计模式
- C++嵌套类/局部类
- [Android UI] 波浪特效的实现
- [leetcode 58] Length of Last Word
- Javabean
- Android.mk文件语法规范及使用模板
- Jdbc练习基础小项目--对个人信息的展示以及增删改查--mvc架构
- hdu5325Crazy Bobo 树形dp
- DDL语句DML语句TCL语句
- 当注释出现乱码时如何调整
- 达内学习日志Day50:使用SpringMVC完成登录操作
- 两个数的最大公倍数