Created
January 9, 2021 05:00
-
-
Save ceth-x86/9f5b3d49b9a9732eb3506797688d05e8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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