leetcode题解-58. Length of Last Word
来源:互联网 发布:微信联系人数据库恢复 编辑:程序博客网 时间:2024/06/05 15:38
题意:给定字符串,求最后一个单词的长度。单词和单词间用空格隔开,若不存在,返回0
分析:这道题难度不是很大。先对输入字符串做预处理,去掉开头和结尾的空格,然后用一个计数器来累计非空格的字符串的长度,遇到空格则停止计数。代码如下:
class Solution { public int lengthOfLastWord(String s) { int len = s.length(); if(len == 0) return 0; int i = len - 1; for(; i >= 0; i--){ if(s.charAt(i) != ' ') break; } int count = 0; for(; i >= 0; i--){ if(s.charAt(i) == ' ') break; else count++; } return count; }}
在discuss中看到一个更为简洁的做法,java一行就可以搞定。当然这需要对字符串操作的函数非常熟悉才行。trim()表示去掉首尾的空格,lastIndexOf表示去掉收尾空格后最后一个空格的位置,记得将结果进行微调。
public int lengthOfLastWord(String s) { return s.trim().length()-s.trim().lastIndexOf(" ")-1;}
阅读全文
0 0
- leetcode题解-58. Length of Last Word
- LeetCode题解:Length of Last Word
- LeetCode题解:Length of Last Word
- LeetCode 58 Length of Last Word题解
- Leetcode题解15 58. Length of Last Word
- 58. Length of Last Word Leetcode Python
- [LeetCode]58.Length of Last Word
- LeetCode --- 58. Length of Last Word
- [Leetcode] 58. Length of Last Word
- [leetcode] 58.Length of Last Word
- LeetCode - 58. Length of Last Word
- <LeetCode OJ> 58. Length of Last Word
- 58. Length of Last Word LeetCode
- 【LeetCode】58. Length of Last Word
- leetcode 58. Length of Last Word
- LeetCode *** 58. Length of Last Word
- LeetCode 58. Length of Last Word
- leetcode-58. Length of Last Word
- python实现验证码
- Android_Java--二分法查找
- unity 《专题系列》资源打包 Asset Bundles 第五节 Asset Bundles 依赖打包和加载
- botan2 编译
- 二叉查找树的
- leetcode题解-58. Length of Last Word
- c:文本文件的读写(simple版)
- Python:读取Word的内容
- matlab fig另存为pdf 图片缺失解决方案
- OpenCV-Mat方式获取图片的像素(二)
- linux命令行的简单操作
- 你不知道的js(中卷)回调
- Java 面试题:百度前200页都在这里了
- java 图像灰度化