leetcode58. Length of Last Word
来源:互联网 发布:淘宝店铺信誉度怎么刷 编辑:程序博客网 时间:2024/06/06 19:32
58. Length of Last Word
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.
解法一
先对字符串去除无用空格,然后倒序输出第一个空格之前的词。
public class Solution { public int lengthOfLastWord(String s) { if (s == null || s.length() == 0) { return 0; } char[] arr = s.toCharArray(); int len = arr.length; String clean = clean(arr, len); char[] cleanArr = clean.toCharArray(); if (cleanArr == null || cleanArr.length == 0) { return 0; } int cleanLen = cleanArr.length; int j = 0; for (int i = cleanLen - 1; i >= 0; i--) { if (cleanArr[i] != ' ') { j++; } else { break; } } return j; } public String clean(char[] arr, int len) { int i = 0, j = 0; while (j < len) { while (j < len && arr[j] == ' ') { j++; } while (j < len && arr[j] != ' ') { arr[i++] = arr[j++]; } while (j < len && arr[j] == ' ') { j++; } if (j < len) { arr[i++] = ' '; } } String s = new String(arr).substring(0, i); return s; }}
解法二
只针对最后一个词,最后一个词之后的空格过滤掉
public class Solution { public int lengthOfLastWord(String s) { if (s == null || s.length() == 0) { return 0; } char[] arr = s.toCharArray(); int len = arr.length; int j = 0; for (int i = len - 1; i >= 0; i--) { while (i >= 0 && arr[i] == ' ') { i--; } while (i >=0 && arr[i] != ' ') { j++; i--; } break; } return j; }}
阅读全文
0 0
- LeetCode58:Length of Last Word
- Leetcode58 Length of Last Word
- LeetCode58----Length of Last Word
- leetcode58---Length of Last Word
- leetcode58:Length of last word
- Leetcode58: Length of Last Word
- leetcode58: Length of Last Word
- Leetcode58.Length of Last Word
- LeetCode58. Length of Last Word
- LeetCode58 Length of Last Word
- Leetcode58. Length of Last Word
- leetcode58. Length of Last Word
- leetcode58. Length of Last Word
- LeetCode58. Length of Last Word
- Leetcode58-Length of Last Word
- LeetCode58——Length of Last Word
- LeetCode58——Length of Last Word
- Length of Last Word
- 滚动抽奖游戏实践
- NDK学习
- Java读取文本文件中文乱码问题(转)
- ubuntu 安装redis两种方式
- 文章解析整理:《入门必看:万字长文带你轻松了解LSTM全貌》
- leetcode58. Length of Last Word
- php使用phpqrcode类库生成带图片LOGO的二维码
- (VIEW控件)PullToRefreshExpandableListView的用法
- DateUtils
- JZ2440点灯程序
- Android 资源文件调用
- mysql数据库data目录下文件说明
- 函数作用域和声明提前
- 回溯法,深度优先遍历