Coding Exercise – Length of Last Word – C++ – Online Judge


Question: Determine the length of the last word in a string given in C, as const char* 

Problem Description: http://oj.leetcode.com/problems/length-of-last-word/

A word is defined as a sequence of non-space characters. If a last word isn’t found (such as ‘ ‘), return zero.

Instead of checking forward the string, we can check from the end. First skip white-spaces, and when it meets the last word-letter, start counting backwards. Simple as that!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
    bool isDig(char c) { // check if alphabet letters
        return ((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z'));     
    }     
 
    int lengthOfLastWord(const char *s) {         
        int i, c = 0;         
        int j = strlen(s);         
        for (i = j - 1; i >= 0 && (!isDig(s[i])); i --) /* do nothing */;
        for (; i >= 0 && (isDig(s[i])); i --) c ++; /* inc length of last word */
        return c;
    }
};
class Solution {
public:
    bool isDig(char c) { // check if alphabet letters
        return ((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z'));     
    }     

    int lengthOfLastWord(const char *s) {         
        int i, c = 0;         
        int j = strlen(s);         
        for (i = j - 1; i >= 0 && (!isDig(s[i])); i --) /* do nothing */;
        for (; i >= 0 && (isDig(s[i])); i --) c ++; /* inc length of last word */
        return c;
    }
};

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
221 words
Last Post: Coding Exercise - N Queen Problem - C++ - Bit Logics - Shortest and Fastest Solution - Online Judge
Next Post: Coding Exercise - First Missing Positive - C++ - Online Judge

The Permanent URL is: Coding Exercise – Length of Last Word – C++ – Online Judge

Leave a Reply