[LeetCode] Length of last word
来源:互联网 发布:狗狗 知乎 编辑:程序博客网 时间:2024/05/29 13:10
Length of last word
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.“word ”
2. " "
3. "word"
4." word "
int lengthOfLastWord(const char *s) { int length = strlen(s); int count = 0; for(int i= length-1; i>=0;i--){ if(s[i] == ' '){ if(count == 0) continue; else return count; } count++; } return count;}
Java解法:
利用split()函数,通过空格“ ”将原字符串分组
public int lengthOfLastWord(String s) { String [] splitStrings = s.split(" "); for(int i=splitStrings.length-1;i>=0;i--){ if(splitStrings[i].length()>0) return splitStrings[i].length(); } return 0; }
public String[] split(String regex)
Splits this string around matches of the given regular expression.This method works as if by invoking the two-argument
split
method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.The string "boo:and:foo", for example, yields the following results with these expressions:
Regex Result :{ "boo", "and", "foo" }o{ "b", "", ":and:f" }- Parameters:
regex
- the delimiting regular expression- Returns:
- the array of strings computed by splitting this string around matches of the given regular expression
- Throws:
PatternSyntaxException
- if the regular expression's syntax is invalid
0 0
- LeetCode: Length of Last Word
- LeetCode Length of Last Word
- LeetCode : Length of Last Word
- [Leetcode] Length of Last Word
- [LeetCode] Length of Last Word
- [LeetCode]Length of Last Word
- [leetcode]Length of Last Word
- Leetcode:Length of Last Word
- LeetCode-Length of Last Word
- [LeetCode] Length of Last Word
- [leetcode] Length of Last Word
- leetcode length of last word
- LeetCode - Length of Last Word
- leetcode:Length of Last Word
- LeetCode:Length of Last Word
- LeetCode | Length of Last Word
- LeetCode - Length of Last Word
- Leetcode: Length of Last Word
- 关于字符设备的操作目录
- Jquer获取页面控件的值 select,checkbox,radio
- 如何在AltiumDesigner中实现两片DDR等长走线
- SQLite三种JDBC驱动的区别
- Python的一些技巧
- [LeetCode] Length of last word
- JavaScript Slider效果实现思路
- JSP引入其它页面
- 数据库未关闭导致的故障分析
- java.lang.NoSuchMethodError: org.springframework.web.context.support.XmlWebApplication的错误
- 如何判断ios设备中是否安装了某款应用
- 字符设备的创建和上层应用如何使用
- c++编译器的工作
- C语言默认参数值的实现