leetcode 58:Length of Last Word
2015-07-09 01:09
501 查看
题目:
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.
分析:
本题考查字符串的操作,一个字符串中可能包含多个单词,单词之间有空格,要求返回字符串中最后一个单词的长度。可以用空格为分隔符划分字符串,将单词存入数组中,得到最后一个单词的长度。分割字符串在数据操作中是必要的一步。
代码:
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.
分析:
本题考查字符串的操作,一个字符串中可能包含多个单词,单词之间有空格,要求返回字符串中最后一个单词的长度。可以用空格为分隔符划分字符串,将单词存入数组中,得到最后一个单词的长度。分割字符串在数据操作中是必要的一步。
代码:
public class lenOfLastWord { public static int lengthOfLastWord(String s){ String wordList[]=s.split(" "); int len=wordList.length; if(len>0){ char[] lastWord=wordList[len-1].toCharArray(); return lastWord.length; }else{ return 0; } } public static void main(String[] args){ String a=" "; int result=lengthOfLastWord(a); System.out.println("lastWord:"+result); } }
相关文章推荐
- reaver如何继续从上次的PIN开始执行
- Hello world xib和纯代码2种实现
- JAVA基础-面向对象之异常与包
- 使用document.write()输出覆盖HTML问题
- 面向对象(五)
- Unity Time类详解
- log4j日志
- LeetCode Isomorphic Strings
- Quartz.NET 入门
- 线程间的通信的几种方式
- Ubuntu下Sublime Text 3 和搜狗拼音输入法安装全套解决方案
- poj 3083 Children of the Candy Corn (DFS+BFS)
- 链表,栈,队列
- 红黑树(2) - 插入操作
- 基础类型封装成NSNumber,NSValue和NSData后存储到NSArray/NSDictionary
- 回忆游戏平台组工作
- C语言 基础60题(5)
- POJ2406 & POJ1961 详细解题思路和AC程序 KMP算法变种
- docker 初试经验
- LeetCode Count Primes