Skip to content

Commit cb98925

Browse files
authored
Merge pull request neetcode-gh#1331 from julienChemillier/patch-18
Add 58 in c language
2 parents 57ef53d + b76f206 commit cb98925

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

c/58-Length-Of-The-Last-Word.c

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/*
2+
Given a string s consisting of words and spaces, return the length of the last word in the string.
3+
4+
Space: O(1)
5+
Time: O(n)
6+
*/
7+
8+
int lengthOfLastWord(char * s){
9+
int last_space=-1; // Index of the last ' '
10+
int last_word=0; // Length of the last word
11+
int i;
12+
for (i=0; s[i]!='\0'; i++) {
13+
if (s[i]==' ') {
14+
if (last_space != (i-1)) {
15+
last_word = i-last_space -1;
16+
}
17+
last_space = i;
18+
}
19+
}
20+
if (last_space == (i-1)) { // if the length wanted is already in last_word
21+
return last_word;
22+
} else {
23+
return i-last_space-1;
24+
}
25+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy