Leetcode Length of Last Word (java)
2015-06-06 18:06
561 查看
Given a string s consists of upper/lower-case alphabets and empty space characters
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 =
return
solution 1:
soulution 2:
' ', 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.
solution 1:
public class Solution { public int lengthOfLastWord(String s) { if(s == null || s.length() ==0) return 0; int result = 0; int length = s.length(); boolean flag = false; for(int i=length-1; i>=0; i--) { char c = s.charAt(i); if((c>='A' && c<='Z') ||( c>='a' && c<='z')) { flag = true; result++; }else { if(flag) { return result; } } } return result; } }
soulution 2:
public class Solution { public int lengthOfLastWord(String s) { if(s == null || s.length() ==0 || s.trim().equals("")) return 0; String[] strs = s.split(" "); String str = strs[strs.length-1]; return str.length(); } }
相关文章推荐
- 使用spring mvc 下载文件
- SpringMvc+Spring+Mybatis+Maven整合
- Java for LeetCode 174 Dungeon Game
- Leetcode Longest Common Prefix (java)
- 学习Java的5个必经阶段
- (二)spring MVC配置
- 最佳新秀SSH十六Struts2它是如何工作的内部
- Java POI导入Excel文件
- Spring @EnableWebMvc
- springMVC bootstarp 用户权限基础框架+即时通讯
- Java读取属性文件简洁工具类
- Eclipse快捷键
- java 生成单号
- NetBeans 下使用EJB的例子
- JVM、Java编译器和Java解释器
- Eclipse上传项目到git.oschina
- Spring事务配置的五种方式
- 使用JSmooth制造java jar文件可以运行exe文件教程图像
- Java设计模式之单例与双重锁定
- 算法编程(JAVA)--八皇后问题