58. Length of Last Word
来源:互联网 发布:手机数据老是自动打开 编辑:程序博客网 时间:2024/05/16 12:21
原题:
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.
Example:
Input: "Hello World"Output: 5
即返回给定字符串最后一个单词的长度。单词之间用空格' ' 隔开。注意实验表明最后一个单词后面可以有空格。
解题思路:
先跳过尾部的空格,然后从尾部遍历,直到发现空格。
AC代码:
public int lengthOfLastWord(String s) { int len = s.length(); if (len == 0) return 0; int i = 0,ret = 0; while (i < len && s.charAt(len - i - 1) == ' ') i++;//去除尾部空格 while (i + ret < len && s.charAt(len - i - ret - 1) != ' ') ret++;//计算最后一个字母长度 return ret; }
阅读全文
1 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
- Windows搭建Deepmind的星际争霸2平台
- 南方电网携手数安时代,保护市民信息安全
- ###Spring @Resource、@Autowired、@Qualifier的注解注入及区别
- 【头条】新华三:融合的力量,既打点,又打面
- UML-基础
- 58. Length of Last Word
- 电阻换算表
- 判断手指上下左右的滑动距离
- 链接
- 相机的使用 --- 拍照,相册导入
- 集合
- 【读书笔记】《What is Mathematics》第一章:自然数
- 流程图
- webstorm git配置