Problem:
Given A string s consists of upper/lower-case alphabets and empty space characters ‘ ‘ , return the length of LA St Word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
For example,
Given S = "Hello World" ,
Return 5 .
Hide TagsStringTest instructions: Gives a string that contains uppercase and lowercase letters and spaces, and the length of the last occurrence of a string that does not contain a space
Thinking:
(1) Fully understanding test instructions is the key to solving this problem. For some special cases: Char *s= ' abc ' (Last is a space), char *s = "A B" (contiguous spaces) to note
(2) Just beginning to consider the use of pointers to calculate the length of the string, the discovery fell into a bottomless abyss, all kinds of special cases to be considered, can be solved, but the comparison around
(3) The use of counting method to solve the problem is the simplest and most efficient, encountered a continuous non-whitespace string start count, encountered a space to save the count results, there are some details to note, in the code has comments
(4) This problem is a comprehensive and detailed analysis of the problem of the ability to deal with
Code
Class Solution {public: int Lengthoflastword (const char *s) { int i=0; int count=0; int length=0; while (* (s+i)! = ') ') { if (* (s+i)! = ') count++; else { if (count>0)//when there are contiguous spaces, prevent the length=count of the last valid count result from being emptied ; count=0; } i++; } if (count!=0)//aftercare: A string ending with a non-whitespace return count; else return length;//End With a space }};
Leetcode | | 58, Length of last Word