We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
2 parents 57ef53d + b76f206 commit cb98925Copy full SHA for cb98925
c/58-Length-Of-The-Last-Word.c
@@ -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