题目
给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中 最后一个 单词的长度。
单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。
题目地址:https://leetcode.cn/problems/length-of-last-word
示例
解法1:转换成字符串数组
作者:本人
思路
将字符串转换成字符数组,再从后往前遍历,空格的ASCLL值是32
class Solution {
public int lengthOfLastWord(String s) {
int result = 0;
char[] sArr = s.toCharArray();
for (int i = sArr.length-1;i>=0;i--){
if (sArr[i]==32&&result==0){
continue;
}if (sArr[i]!=32){
result++;
continue;
}if (sArr[i]==32&&result>0){
return result;
}
}
return result;
}
}
效果
解法2:反向遍历
作者:力扣官方
思路
与我的方法相似,只是这里是用了字符串中的 charAt方法
class Solution {
public int lengthOfLastWord(String s) {
int index = s.length() - 1;
while (s.charAt(index) == ' ') {
index--;
}
int wordLength = 0;
while (index >= 0 && s.charAt(index) != ' ') {
wordLength++;
index--;
}
return wordLength;
}
}
效果
比我的方法1 节省空间