This topic is classified as a simple topic, but it is not easy for me to say. Some topics are algorithm problems, some of which are detailed. Algorithms are often difficult to think about, and details are often difficult to achieve. both of which are difficult, can not be considered a simple problem.
The difficulty of this problem lies in the intuitive to be divided into a number of situations to discuss, and actually can do simple induction, is the difficulty greatly reduced. And the induction, refining ability and how many people can do it? So the problem is very difficult.
Different case:
(1) ""
(2) "a"
(3) " "
(4) "a B"
(5) "ABCD"
(6) "a"
Solve this problem, if the idea is wrong, it will be very troublesome. For example, a two-pointer approach would be cumbersome, since the position relationship of two pointers does not have an invariant. If this idea is not feasible, it is necessary to switch in time. For example:
(1) from the backward forward scanning, because only the last word length, so cut in, the problem is much simpler. It's enough to think of space and out of bounds.
int Lengthoflastword (const char *s) { int length =-1; while (s[++length]! = NULL); for (int i = length-1; I >= 0; i--) { if (s[i]! = ") { int marker = i; while (---->= 0 && s[i]! = "); return marker-i; } } return 0; }
(2) and then the past. However, regardless of the other cases in the iteration, only the length of the last word is considered.
int Lengthoflastword (const char *s) { int n; int q, cnt=0; for (q = 0; S[q]! = ' + '; q++) { if (s[q]! = ') cnt++; else if (s[q+1]! = "&& s[q+1]! = ' \") cnt = 0; } return CNT;}
Simplified version:
int Lengthoflastword (const char *s) { int len = 0, Lastlen = 0, i = 0; while (*s) { if (*s++ = =) len = 0; else Lastlen = ++len; } return Lastlen;}
(3) can also be used stringstream, but this practice does not promote
int Lengthoflastword (const char *s) { StringStream stream (s); string T; while (stream >> t); return T.length (); }
Count the length of the last word of a string