[面试备忘]计算字符串相似度 & 无头单链删非头尾节点 & 基于前续中续重建二叉树

鞭惩之美-3.3计算字符串相似度

鞭惩之美-3.4无头单链删除节点

鞭惩之美-3.9重建二茶树

View Code
 1 #include <iostream>
2 #include <cstring>
3 #include "general.h"
4
5 //鞭惩之美-3.3计算字符串相似度
6 int stepCount(const char* preArray, int preSize, const char* postArray, int postSize)
7 {
8 if (!preSize || !postSize) {
9 return preSize + postSize;
10 }
11 if (*preArray == *postArray) {
12 return stepCount(reinterpret_cast<const char*>(preArray + 1), preSize - 1,
13 reinterpret_cast<const char*>(postArray + 1), postSize - 1);
14 }
15 return MIN(MIN(stepCount(preArray + 1, preSize - 1, postArray, postSize),
16 stepCount(preArray, preSize, postArray + 1, postSize - 1)),
17 stepCount(preArray + 1, preSize - 1, postArray + 1, postSize - 1)) + 1;
18 }
19
20 //鞭惩之美-3.4无头单链删除节点
21 void deleteSpecificNode(PNODE pNode)
22 {
23 if (!pNode || !pNode->next) {
24 return;
25 }
26 PNODE toDelete = pNode->next;
27 pNode->value = toDelete->value;
28 pNode->next = toDelete->next;
29 delete toDelete;
30 }
31
32 //鞭惩之美-3.9重建二茶树
33 void reBuildBinaryTree(const char* pPreOrder, const char* pInOrder, int length, PTNODE& root)
34 {
35 if (length == 0) {
36 root = NULL;
37 return;
38 }
39 root = new TNODE();
40 root->value = pPreOrder[0];
41 int inOrderRootIndex = 0;
42 for ( ; inOrderRootIndex != length; ++inOrderRootIndex) {
43 if (pInOrder[inOrderRootIndex] == pPreOrder[0]) {
44 break;
45 }
46 }
47 reBuildBinaryTree(reinterpret_cast<const char*>(pPreOrder + 1), pInOrder,
48 inOrderRootIndex, root->left);
49 reBuildBinaryTree(reinterpret_cast<const char*>(pPreOrder + 1 + inOrderRootIndex),
50 reinterpret_cast<const char*>(pInOrder + 1 + inOrderRootIndex),
51 length - 1 - inOrderRootIndex, root->right);
52 }
53
54 int main()
55 {
56 //test for stepCount
57 char a[] = "abcd";
58 char b[] = "efhg";
59 std::cout << static_cast<float>(1 / static_cast<float>(1+stepCount(a, strlen(a), b, strlen(b)))) << std::endl;;
60 //test for deleteSpecificNode
61 PNODE head = createList(10);
62 printList(head);
63 PNODE temp = head;
64 for (int index = 0; index != 5 && temp != NULL; ++index) {
65 temp = temp->next;
66 }
67 std::cout << temp->value << std::endl;
68 deleteSpecificNode(temp);
69 printList(head);
70 destroyList(head);
71 //test for reBuildBinaryTree
72 char preOrder[] = "abcdef";
73 char inOrder[] = "abcdef";
74 PTNODE root = NULL;
75 reBuildBinaryTree(preOrder, inOrder, strlen(preOrder), root);
76 preOrderPrint(root);
77 inOrderPrint(root);
78 postOrderPrint(root);
79 return 0;
80 }
posted @ 2011-09-05 14:58  lifengzhong  阅读(154)  评论(0编辑  收藏  举报