Description
Given a string s consists of upper/lower-case alphabets and empty space characters' '
, return the length of last 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"
,
return5
.
Analysis
Time limit will excceed if we search in a straight
method. Write down some results and you’ll find the answer is in the Fibonacci sequence.
n | result |
---|---|
1 | 1 |
2 | 2 |
3 | 3 |
4 | 5 |
5 | 8 |
Code
Version 1 (TLE)
class Solution {
public:
int climbStairs(int n) {
result = 0;
climb(n);
return result;
}
private:
int result;
void climb(int target){
if (target == 0){
result++;
return;
}
if (target >= 2){
climb(target-2);
climb(target-1);
return;
}
climb(target-1);
}
};
Version 2 (Fibonacci sequence)
class Solution {
public:
int climbStairs(int n) {
int a = 1, b = 1;
while (n--){
b = b + a;
a = b - a;
}
return a;
}
};
Appendix
- Link: https://leetcode.com/problems/climbing-stairs/
- Run Time: 0ms