Created
January 16, 2020 02:14
-
-
Save adamkorg/eda4764ec11da3c3ce932e614636f224 to your computer and use it in GitHub Desktop.
Leetcode 58: Length of Last Word
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
#include <iostream> | |
#include <string> | |
using namespace std; | |
int lengthOfLastWord(string s) { | |
int n = s.size(); | |
int i = n-1; | |
while (i >= 0 && s[i]==' ') i--; //skip trailing whitespace | |
int last = i; | |
for ( ; i >= 0; --i) { | |
if (s[i] == ' ') return n-(i+1); | |
} | |
return last-i; | |
} | |
int main() { | |
string s = "Hello World"; | |
cout << lengthOfLastWord(s) << "\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment