Leet Code OJ 58. Length of Last Word [Difficulty: Easy]
来源:互联网 发布:车万翔老师的python课 编辑:程序博客网 时间:2024/05/22 20:25
题目:
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.
翻译:
给定一个字符串,它是由大小写字母和空格组成的,返回字符串中最后一个单词的长度。
如果最后一个单词不存在,就返回0.
提示:一个单词是指一个只由非空格的字符组成的字符串序列。
分析:
有一点题目中没有说明的是,假如最后是空格的话,如何处理。经过测试,发现最后是空格的话,还是返回上一个单词的长度,并不会清零。
代码:
public class Solution { public int lengthOfLastWord(String s) { char[] arr=s.toCharArray(); int count=0; boolean needClean=false; for(int i=0;i<arr.length;i++){ if(arr[i]!=' '){ if(needClean){ count=0; needClean=false; } count++; }else{ needClean=true; } } return count; }}
1 0
- Leet Code OJ 58. Length of Last Word [Difficulty: Easy]
- [leet code] Length of Last Word
- Leet Code OJ 231. Power of Two [Difficulty: Easy]
- Leet Code OJ 326. Power of Three [Difficulty: Easy]
- Leet Code OJ 191. Number of 1 Bits [Difficulty: Easy]
- 58. Length of Last Word [easy] (Python)
- <LeetCode OJ> 58. Length of Last Word
- Leet Code OJ 104. Maximum Depth of Binary Tree [Difficulty: Easy]
- Leet Code OJ 235. Lowest Common Ancestor of a Binary Search Tree [Difficulty: Easy]
- Leet Code OJ 292. Nim Game [Difficulty: Easy]
- Leet Code OJ 242. Valid Anagram [Difficulty: Easy]
- Leet Code OJ 258. Add Digits [Difficulty: Easy]
- Leet Code OJ 226. Invert Binary Tree [Difficulty: Easy]
- Leet Code OJ 283. Move Zeroes [Difficulty: Easy]
- Leet Code OJ 217. Contains Duplicate [Difficulty: Easy]
- Leet Code OJ 169. Majority Element [Difficulty: Easy]
- Leet Code OJ 263. Ugly Number [Difficulty: Easy]
- Leet Code OJ 100. Same Tree [Difficulty: Easy]
- getparameter和getattribution的区别的 java详细
- cocos2d-js自定义CheckBox
- php中strtotime与mktime的Y2K38漏洞(时间最长为2038年)
- Android Linux Kernel 移植流程
- 《Java程序设计基础》 第2章手记
- Leet Code OJ 58. Length of Last Word [Difficulty: Easy]
- Android Activity:四种启动模式,Intent Flags和任务栈
- device tree 的device node 怎么才能device add to bus???
- Android万能标题栏
- 解析几何:第五章 二次曲线(2)抛物线 一般二次曲线
- Python_urllib.urlopen
- React 标签和属性支持
- AngularJS中ng-class使用方法
- 安装ruby一定要注意的一步(ruby -v和 rbenv version结果不一致)