Leetcode--easy系列4

#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".

存储在字符串中的二进制数相加。下面的代码还可以优化,边相加边进行进位判断。测试时,a,b采用数组形式,否则如果指向字符串常量,是不容许修改字符串中的值,从而导致错误。

char* addBinary(char* a, char* b) {
    int i,j=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;

	//指针p指向 a/b中长度较长的 q指向较短的
	if(len1 == len2)
	{
		p = a;
		q = b;
	}
	else if(len1 > len2)
	{
		p = a;
		q = b;
	}
	else if(len1 < len2)
	{
		p = b;
		q = a;
	}

	if(len1==0)
		return b;
	if(len2==0)
		return a;

	for(i=len_min-1; i>=0; i--)
	{
		p[len_max-1-j] += (q[len_min-1-j]-'0');
		j++;
	}
    //判断是否最高位有进位
	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];
    }
}
时间: 2024-08-25 02:27:16

Leetcode--easy系列4的相关文章

Leetcode permutation 系列

关于permutation的讲解,请参见http://blog.csdn.net/xuqingict/article/details/24840183 下列题目的讲解均是基于上面的文章: 题1: Next Permutation Total Accepted: 8066 Total Submissions: 32493My Submissions Implement next permutation, which rearranges numbers into the lexicographic

【Leetcode长征系列】Letter Combinations of a Phone Number

原题: Given a digit string, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Input:Digit string "23" Output: ["ad", "ae"

【Leetcode长征系列】Merge k Sorted Lists

原题: Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 思路:两条两条地合并.时间复杂度为O(n),n为所有链表节点和. 代码: /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) :

[LeetCode蠕动系列]Sort List

这题前一阵子就看到了,一直没时间做,昨晚睡前想了想,要求n*log(n)以内的时间复杂度,第一时间想到的就是归并.快排和希尔排序(注:希尔排序时间为O(n^1.3),在数据量大于2的情况下小于n*log(n)),个人以为,链表的特性更适合归并,所以采用归并排序,实现的merge代码如下: public static ListNode merge(ListNode rhead, ListNode lhead) { ListNode head = null; if (rhead.val <= lhe

HDU 2045不easy系列之三LELE的RPG难题(趋向于DP的递推)

不easy系列之(3)-- LELE的RPG难题 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 30222 Accepted Submission(s): 12144 Problem Description 人称"AC女之杀手"的超级偶像LELE近期忽然玩起了深沉,这可急坏了众多"Cole"(LELE的粉丝,即

【Leetcode长征系列】Construct Binary Tree from Inorder and Postorder Traversal

原题: Given inorder and postorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. 思路:和上一题一样,后续我们可以通过最后一个值得到根的值,同样可以通过定位根的值得到左右子树的子集,递归求解即可. 代码: /** * Definition for binary tree * struct Tre

【Leetcode长征系列】Single Number II

原题: Given an array of integers, every element appears three times except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 思路: 用一个32位的数组存每一位bit值之后.得到答案后每一位除

【Leetcode长征系列】Pow(x, n)

原题: Implement pow(x, n). 思路:递归计算pow. class Solution { public: double pow(double x, int n) { long long int mid = n/2; int d = n%2; if(n==0) return 1; if(n==1) return x; if(d==1) return pow(x, (n/2)+1) * pow(x, n/2); else return pow(x, n/2) * pow(x, n/

【Leetcode长征系列】Sqrt(x)

原题: Implement int sqrt(int x). Compute and return the square root of x. ==============================以下为引用==================================== 牛顿迭代法 为了方便理解,就先以本题为例: 计算x2 = n的解,令f(x)=x2-n,相当于求解f(x)=0的解,如左图所示. 首先取x0,如果x0不是解,做一个经过(x0,f(x0))这个点的切线,与x轴的交

【Leetcode长征系列】Balanced Binary Tree

原题: Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees ofevery node never differ by more than 1. 思路:递归判断左右子树是否为BST. 代码: /** * Def