leetcode -- 58. Length of Last Word【遍历数组的次序:前后】
来源:互联网 发布:最早的网络竞技游戏 编辑:程序博客网 时间:2024/05/21 17:00
题目
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
.
题意
给定一个字符串 ,返回这个字符串最后一个单词的长度。
分析及解答
解答1:(从后往前)【更快】
public class Solution { public int lengthOfLastWord(String s) { if(s.equals("")) return 0; char[] array = s.toCharArray(); boolean isPreSpace = true; boolean isCurrentSpace = false; int count = 0; for(int i = array.length-1; i >= 0 ;i--){ isCurrentSpace = (array[i] == ' '); if(isPreSpace){ if(!isCurrentSpace){ count =1; } }else{ if(!isCurrentSpace){ count ++; }else{ break; } } isPreSpace = isCurrentSpace; } return count; }}
解法2:(从前往后)
public int lengthOfLastWord(String s) { if(s.equals("")) return 0; char[] array = s.toCharArray(); boolean isPreSpace = true; boolean isCurrentSpace = false; int count = 0; for(char ch : array){ isCurrentSpace = (ch == ' '); if(isPreSpace){ if(!isCurrentSpace){ count =1; } }else{ if(!isCurrentSpace){ count ++; } } isPreSpace = isCurrentSpace; } return count; }
阅读全文
0 0
- leetcode -- 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
- LeetCode-58.Length of Last Word
- [leetcode] 58. Length of Last Word
- LeetCode 58. Length of Last Word
- Leetcode-58. Length of Last Word
- 新一代大数据技术架构
- 拦截器Interceptor总结
- 基于SSM的CRUD小栗子
- 实验探究 ioremap
- test STL
- leetcode -- 58. Length of Last Word【遍历数组的次序:前后】
- 我的备用书单
- 539. Minimum Time Difference
- uva 10795 A Different Task (汉诺塔升级)
- 一次生日Party可能有p人或者q人参加,现准备有一个大蛋糕.问最少要将蛋糕切成多少块(每块大小不一定相等),才能使p人或者q人出席的任何一种情况,都能平均将蛋糕分食
- Strus2类型转换器心得
- 合并两个排序链表
- JavaScript_2
- js获取一个字符串的某个字符的索引