Wednesday, February 17, 2016

LeetCode Q58: Length of Last Word

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.

Straightforward solution, just take care of continuous training empty signs.


class Solution {
public:
int lengthOfLastWord(string s) {
int count=0;
int emptyMet=1;
for(int i=0; i<s.length(); ++i){
char c=s[i];
if(c==' '){
emptyMet=1;
continue;
}
if(c!=' '&&emptyMet==1){
count=1;
emptyMet=0;
continue;
}
if(c!=' '&&emptyMet==0)
count++;
}
return count;
}
};


Round 2 Solution:
class Solution {
public:
int lengthOfLastWord(string s) {
int len=0;
for(int i=0; i<s.length(); i++){
if(i-1>=0 && s[i-1]==' ' && s[i]!=' ')
len=0;
if(s[i]!=' ')
len++;
}
return len;
}
};
view raw Q58-2.cpp hosted with ❤ by GitHub

No comments:

Post a Comment