给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中 最后一个 单词的长度。
单词 是指仅由字母组成、不包含任何空格字符的最大
子字符串。
class Solution {
public int lengthOfLastWord(String s) {
String[] newArr = s.split(" ");
String last = newArr[newArr.length - 1];
return last.length();
}
}
复杂度分析:
时间复杂度为 O(n),其中 n 是字符串 s 的长度。
空间复杂度为 O(n)。
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;
}
}
复杂度分析:
时间复杂度:O(n),其中 n 是字符串的长度。最多需要反向遍历字符串一次。
空间复杂度:O(1)。