58. Length of Last Word
1.問題
2.想法
提問
最後面的字串碰不到space, 是否也算一個完整的字串?
function header, parameter
test input
說明想法
向前掃瞄字串的每個字母, 當不等於space時cnt++, 碰到space時讓lastCnt = cnt
分成兩種情況回傳長度:
當最後面的字串最後沒有space: 回傳cnt
當最後面的字串有space: 回傳lastCnt
測試計算複雜度
O(N)
3.程式碼
class Solution {
public:
int lengthOfLastWord(string s) {
int size = s.length();
int cnt = 0, lastCnt = 0;
for (int i = 0; i < size; ++i) {
if (s[i] != ' ') {
++cnt;
} else {
if (cnt != 0) {
lastCnt = cnt;
}
cnt = 0;
}
}
if (s[size - 1] != ' ') {
return cnt;
}
return lastCnt;
}
};
Last updated