Skip to content

Instantly share code, notes, and snippets.

@pdu
Created February 17, 2013 11:23
Show Gist options
  • Select an option

  • Save pdu/4971052 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4971052 to your computer and use it in GitHub Desktop.
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 consists of non-space characters only. For example, Given s = "Hello World", return 5. http://leetcode.com/onlinejudge#que…
class Solution {
public:
int lengthOfLastWord(const char *s) {
int ans = 0;
int cnt = 0;
for (int i = 0; s[i] != 0; ++i) {
if (s[i] == ' ')
cnt = 0;
else {
cnt++;
ans = cnt;
}
}
return ans;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment