題目: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 consist
解題代碼一(從后往前掃描):
// 逆序掃描// 時(shí)間復(fù)雜度 O(n),空間復(fù)雜度 O(1)class Solution {public: int lengthOfLastWord(string s) { int len = 0; int i = s.size() - 1; while (i >= 0) if (s[i] == ' ') --i; else break; while (i >= 0) if (s[i] != ' ') ++len, --i; else break; return len; }};解題代碼二(從前往后掃描):
// 順序掃描,記錄每個(gè) word 的長度// 時(shí)間復(fù)雜度 O(n),空間復(fù)雜度 O(1)class Solution {public: int lengthOfLastWord(const string& s) { int len = 0; for (int i = 0; i < s.size(); ) { if (s[i] != ' ') ++len, ++i; else { ++i; if (i < s.size() && s[i] != ' ') ++len; } } return len; }};新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注