Skip to content

Instantly share code, notes, and snippets.

@adamkorg
Created January 16, 2020 02:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamkorg/eda4764ec11da3c3ce932e614636f224 to your computer and use it in GitHub Desktop.
Save adamkorg/eda4764ec11da3c3ce932e614636f224 to your computer and use it in GitHub Desktop.
Leetcode 58: Length of Last Word
#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