#58 Length of Last Word
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"
,
return 5
.
int lengthOfLastWord(char* s) {
int count = 0;
int len = strlen(s);
int i = 0,j = len-1;
while(s[j]==' ')//忽略空格
j--;
while(j>=i)
{
if(s[j] != ' ')
count++;
else
break;
j--;
}
return count;
}
#66 Plus One
Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
给定存储在字符串中的非负数,返回其+1后的结果(字符串形式)当然字符串存储的特点是方便大数计算,所以是不能先从字符串转换为数字再+1的。
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* plusOne(int* digits, int digitsSize, int* returnSize) {
int i = digitsSize-1;
int *result;//返回字符串
digits[i]++;//加1
/*如果>=10就进位*/
while(digits[i]>=10 && i>=1)
{
digits[i] = digits[i]-10;
i--;
digits[i]++;
}
/*判断最高位是否产生进位--是否增加字符串长度*/
if(digits[0]>=10)
{
*returnSize = digitsSize+1;
result = (int *)malloc(sizeof(int)*(digitsSize+1));
digits[0] = digits[0]-10;
for(i=0;i<digitsSize;i++)
result[i+1] = digits[i];
result[0] = 1;
}
else
{
*returnSize = digitsSize;
result = digits;
}
return result;
}
#67 Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
char* addBinary(char* a, char* b) {
int i,j = 0,k = 0;
int len1 = strlen(a);
int len2 = strlen(b);
char *p,*q,*r;
int len_max = (len1>=len2) ? len1:len2;
int len_min = (len1<=len2) ? len1:len2;
if(len1 == 0)
return b;
if(len2 == 0)
return a;
//指针p指向 a/b中长度较长的 q指向较短的
if(len1 >= len2)
{
p = a;
q = b;
}
else
{
p = b;
q = a;
}
//p=p+q---先相加----数的低位放在存储的高位
for(j = len_min-1; j >= 0; j--)
{
p[len_max-1-k] += (q[j] - '0');
k++;
}
//判断是否最高位有进位
for(i = len_max-1; i >= 1; i--)
{
if(p[i] >= '2')
{
p[i] -= 2;
p[i-1]++;
}
}
//判断最高位
if( p[0]-'0'<2 )
return p;//位数不变
else
{
p[0] -= 2;//溢出
r = (char *)malloc(sizeof(char)*(len_max+2));
r[0] = '1';//进位
for(i = 1; i <= len_max; i++)
r[i] = p[i-1];
r[len_max+1]='\0';
return r;
}
}
#70 Climbing Stairs
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
类似这样的问题有很多,如猴子摘桃,走台阶,实质都是裴波那切数列。f(n) = f(n-1)+f(n-2).直接使用递归,如下,但是提交结果显示 Time Limit Exceeded
int climbStairs(int n) {
if(n==1)
return 1;
if(n==2)
return 2;
if(n>2)
return climbStairs(n-1)+climbStairs(n-2);
}
因为使用递归时,会重复计算。DP算法就是保存中间结果来避免计算重复子问题。改进如下:
int climbStairs(int n) {
int i,*a;
if(n==1)
return 1;
if(n==2)
return 2;
if(n>2)
{
a=(int *)malloc(sizeof(int)*n);
a[0]=1;
a[1]=2;
for(i=2;i<n;i++)
a[i]=a[i-1]+a[i-2];
return a[n-1];
}
}