[leetcode]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.
Example:
Input: "Hello World"
Output: 5
解法一
思路
这道题思路很简单,就是用个计数器,碰到空格就重置为0,这样遍历一遍之后计数器的值就为最后一个字母的长度。但是这是在建立在字符串首位都没有空格的情况下,所以我们刚开始需要把首位的字符串都去掉。
代码
class Solution {
public int lengthOfLastWord(String s) {
if(s.length() == 0) return 0;
int left = 0;
int right = s.length()-1;
while(s.charAt(left) == ' ' && left < right) ++left;
while(s.charAt(right) == ' '&& right > left) --right;
if(left == right && s.charAt(left) == ' ') return 0;
int length = 0;
for(int i = left; i <= right; i++) {
if(s.charAt(i) == ' ')
length = 0;
else length++;
}
return length;
}
}
解法二
思路
我们要求的是最后一个单词的长度,所以我们只需要去除字符串尾部的空格,然后从尾部开始计数一直到遇见第一个空格为止。
代码
class Solution {
public int lengthOfLastWord(String s) {
if(s.length() == 0) return 0;
int len = s.length() - 1;
while(s.charAt(len) == ' ' && len > 0) --len;
int count = 0;
for(int i = len; i >= 0; i--) {
if(s.charAt(i) != ' ')
count ++;
else break;
}
return count;
}
}
解法三
这种方法没什么意思,但是很简洁。
class Solution {
public int lengthOfLastWord(String s) {
return
s.trim().length() - s.trim().lastIndexOf(' ') - 1;
}
}