Skip to content

Instantly share code, notes, and snippets.

@ceth-x86
Created January 9, 2021 05:00
Show Gist options
  • Save ceth-x86/9f5b3d49b9a9732eb3506797688d05e8 to your computer and use it in GitHub Desktop.
Save ceth-x86/9f5b3d49b9a9732eb3506797688d05e8 to your computer and use it in GitHub Desktop.
class Solution {
public:
int lengthOfLastWord(string s) {
int len = 0, tail = s.length() - 1;
while (tail >= 0 && s[tail] == ' ') tail--;
while (tail >= 0 && s[tail] != ' ') {
len++;
tail--;
}
return len;
}
};
class Solution {
public:
int lengthOfLastWord(string s) {
int result = 0; int prev = 0;
for (size_t i = 0; i < s.size(); i++) {
if (s[i] != ' ') {
result += 1;
} else {
if (result != 0) {
prev = result;
}
result = 0;
}
}
if (result != 0) {
return result;
} else {
return prev;
}
}
};
class Solution:
def lengthOfLastWord(self, s: str) -> int:
result = 0; prev = 0
for ch in s:
if ch != ' ':
result += 1
else:
if result != 0:
prev = result
result = 0
return result if result != 0 else prev
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment