58. Length of Last Word - Easy
前往題目
想法
trim
前後- 雙指針直到最後一個
word
思路
雖然自己寫出來了,但看了neetcode
大大的解法覺得更好
- 從後面開始,跳過所有空格
- 遇到字之後繼續往前並紀錄走過幾個字
- 再次遇到空格時就是完成紀錄,直接回傳字數
Code
自己寫的部分,用到trim
然後把每個字都走過一遍直到最後一個
class Solution {
public int lengthOfLastWord(String s) {
s = s.trim();
int l = 0, r = 0;
while (r < s.length()) {
if (s.charAt(r) == ' ') {
l = r + 1;
}
++r;
}
return r - l;
}
}
Neetcode
的解法更好,因為沒有用到built-in function
,而且從後面開始大部分case
應該都比我上面的解快一點,雖然我上面的解也是O(n)
,不過多了trim
還有從前面到後面
class Solution {
public int lengthOfLastWord(String s) {
int index = s.length() - 1;
int res = 0;
while (s.charAt(index) == ' ') {
--index;
}
while (index >= 0 && s.charAt(index) != ' ') {
++res;
--index;
}
return res;
}
}
58. Length of Last Word - Easy
https://f88083.github.io/2024/05/09/58-Length-of-Last-Word-Easy/