Skip to content

Commit

Permalink
Add 58 in c language
Browse files Browse the repository at this point in the history
  • Loading branch information
julienChemillier authored Oct 27, 2022
1 parent 98b6666 commit e3afd3d
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions c/58-length-of-the-last-word.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
Given a string s consisting of words and spaces, return the length of the last word in the string.
Space: O(1)
Time: O(n)
*/

int lengthOfLastWord(char * s){
int last_space=-1; // Index of the last ' '
int last_word=0; // Length of the last word
int i;
for (i=0; s[i]!='\0'; i++) {
if (s[i]==' ') {
if (last_space != (i-1)) {
last_word = i-last_space -1;
}
last_space = i;
}
}
if (last_space == (i-1)) { // if the length wanted is already in last_word
return last_word;
} else {
return i-last_space-1;
}
}

0 comments on commit e3afd3d

Please sign in to comment.