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!
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) —
204 wordsLast 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