阿里校招附加题2014-8-29

附加题:

1、给定一个query和一个text,均由小写字母组成。要求在text中找出以同样顺序连续出现在query中最长连续字母序列的长度。例如,query为“acbac”,text为“acaccbabb”,那么text中的“cba”为最长的连续出现在query中的字符序列,因此,返回结果应该为其长度3。请注意程序效率。

//最长公共子串(LCS)
//str1为横向,str2为纵向
const string LCS(const string& str1, const string& str2) {
	int xlen = str1.size(); //横向长度
	vector<int> tmp(xlen);	//保存矩阵的上一行
	vector<int> arr(tmp);	//当前行
	int ylen = str2.size(); //纵向长度
	int maxelem = 0;			//矩阵元素中的最大值
	int pos = 0;			//矩阵元素最大值出现在第几列
	for(int i = 0; i < ylen; i++) {
		//取字符中的一个字符
		string s = str2.substr(i, 1);
		arr.assign(xlen, 0);	//数组清0
		for (int j = 0; j < xlen; j++) {
			//s与每一个字符进行比较
			if (str1.compare(j,1,s) == 0) {
				if (j == 0)
					arr[j] = 1;
				else
					arr[j] = tmp[j-1] +1;
				if (arr[j] > maxelem) {
					maxelem = arr[j];
					pos = j;
				}
			}
		}
		//tmp保存上一行
		tmp.assign(arr.begin(), arr.end());
	}
	string res = str1.substr(pos-maxelem+1, maxelem);
	return res;
}



2、写一个函数,输入一个二叉树,树中每个节点存放了一个整数值,函数返回这棵树中相差最大的两个节点间的差的绝对值。请注意程序效率。

#include <iostream>

using namespace std;

struct TreeNode {
	int data;
	TreeNode* left;
	TreeNode* right;
};

//创建一个结点
TreeNode* CreateTreeNode(int val)
{
	TreeNode* p = new TreeNode;
	p->data = val;
	p->left = NULL;
	p->right = NULL;
	return p;
}

//连接结点
void ConnectTreeNode(TreeNode* parent, TreeNode* left, TreeNode* right)
{
	if(parent != NULL) {
		parent->left = left;
		parent->right = right;
	}
}

int GetTreeMax(TreeNode* root)
{
	if (root == NULL)
		return INT_MIN;	
	
	int left_max = GetTreeMax(root->left);	
	int right_max = GetTreeMax(root->right);
	int max = left_max > right_max ? left_max : right_max;

	return max > root->data ? max : root->data;
}

int GetTreeMin(TreeNode* root)
{
	if (root == NULL)
		return INT_MAX;

	int left_min = GetTreeMin(root->left);
	int right_min = GetTreeMin(root->right);
	int min = left_min > right_min ? right_min : left_min;

	return root->data > min ? min : root->data;
}

int getAbs(TreeNode *root)
{
	return GetTreeMax(root) - GetTreeMin(root);
}


int _tmain(int argc, _TCHAR* argv[])
{
	//创建结点
	TreeNode* pNode1 = CreateTreeNode(10);
	TreeNode* pNode2 = CreateTreeNode(23);
	TreeNode* pNode3 = CreateTreeNode(-32);
	TreeNode* pNode4 = CreateTreeNode(40);
	TreeNode* pNode5 = CreateTreeNode(5);
	TreeNode* pNode6 = CreateTreeNode(62);
	TreeNode* pNode7 = CreateTreeNode(7);

	//连接
	ConnectTreeNode(pNode1, pNode2, pNode3);
	ConnectTreeNode(pNode2, pNode4, pNode5);
	ConnectTreeNode(pNode3, NULL, pNode6);
	ConnectTreeNode(pNode5, pNode7, NULL);

	cout << GetTreeMax(pNode1) << endl;
	cout << GetTreeMin(pNode1) << endl;
	cout << getAbs(pNode1) << endl;
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值