58. Length of Last Word
来源:互联网 发布:逆袭网络剧百度云网盘 编辑:程序博客网 时间:2024/05/29 16:30
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
.
第一种方法:因为之前写了一个reverse函数,就想着用现成的,这个真的太繁琐,晕!
public void reverse(char[] a, int start,int end) { if(a==null||start<0||end>a.length-1) return; while(start<=end) { char b=a[start]; a[start]=a[end]; a[end]=b; start++; end--; } }public int lengthOfLastWord(String s) { if(s.length()==0||s==null) return 0; char[] c=s.toCharArray(); int res=0; int len=c.length; int cnt=0; for(int i=len-1;i>=0;i--) { if(c[i]==' ') cnt++; else break; } if(cnt>0) reverse(c,0,len-1-cnt); else reverse(c,0,len-1); for(int i=0;i<len;i++) { if(c[i]!=' ') { res++; } else break; } return res; }
第二种方法:用split。两行
public int lengthOfLastWord1(String s) { String[] ss=s.split(" "); return ss.length==0?0:ss[ss.length-1].length(); }
第三种方法:从后往前res++
public static int lengthOfLastWord2(String s) { int res=0; int i=s.length()-1; while(i>=0&&s.charAt(i)==' ') { i--; } while(i>=0&&s.charAt(i)!=' ') { res++; i--; } return res; }
0 0
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58.Length of Last Word
- 乌班图系统安装
- 止于至善
- Golang 学习笔记:HTTP, TCP/IP, UDP
- 安卓自定义圆形imageview
- linux 中fork函数详解
- 58. Length of Last Word
- 实现网站的响应式轮播图
- 回溯法-leetcode
- Flex 布局语法教程
- GraphX上的一些简单应用
- TCP协议中URG、PSH及三次握手与四次挥手
- github常见操作和常见错误!错误提示:fatal: remote origin already exists.
- 使用FloatingActionButton时出现的问题
- c++智能指针的原理与简单实现