Length of Last Word
来源:互联网 发布:linux基础教程第二版 编辑:程序博客网 时间:2024/06/14 00:11
题目要求:
在给定字符串中找出最后一个word的长度,word指被空格符“ ”截断的部分。即”Hello World”
中最后一个word是指World,所以其长度是5。
解题思路:
设置一个标识 reset(当遇到非空格符时根据reset来判断是否要重置str)。
比如上面的”Hello World”,当遇到第一个字符H时,reset为false。将H赋值给str,往后走遇到第一个空格符“ ”时,此时将reset赋值true。当再次遇到非空格符W时,因为reset为true,此时重置str。然后重复上述过程得到答案。
AC代码:
public class Solution { public int lengthOfLastWord(String s) { boolean reset = false; String str = ""; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (' ' != c) { if (reset) { str = ""; reset = false; } str += c; } else { reset = true; } } return str.length(); }}
0 0
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- 11单元和12单元作业
- P1057 传球游戏 洛谷
- CentOS中使用VeraCrypt(四):进阶操作
- 多个源程序组成程序编译问题
- Unity问题集合
- Length of Last Word
- 学习Android中广播的总结
- Android项目重构之路:架构篇
- .NetCore~C#6的一些新特性
- spring mvc设置应答体的content type
- 系统广播
- android studio 出现Error:Execution failed for task ':app:buildInfoDebugLoader'.的解决办法
- java基础 --自己随手复习
- Android系统广播大全及开机自启动的Service