2015-09-09 [一点资讯]--数据抓取和处理工程师--1面
时间:2015-09-09 10:00 ~ 11:00
地点:北京市海淀区王庄路1号 清华同方科技广场D座 西区 7层
1. 实现链表加法
链接:https://github.com/loverszhaokai/ALG/blob/master/src/add_long.cc
两次反转。
// Reverse a list // E.g. 1->2->3 after reverse is: 3->2->1 static ListNode *reverse(ListNode *head) { ListNode *pre_node = NULL, *next_node; while (head) { next_node = head->next; head->next = pre_node; pre_node = head; head = next_node; } return pre_node; } ListNode *add_long(ListNode *head1, ListNode *head2) { if (head1 == NULL && head2 == NULL) return NULL; // Reverse head1 and head2 head1 = reverse(head1); head2 = reverse(head2); ListNode *orig_head1 = head1; ListNode *orig_head2 = head2; ListNode pseudo_head(0); // pseudo_head.next is the real head ListNode *pre_node = &pseudo_head; ListNode *node; int carry = 0; while (head1 && head2) { carry += head1->val + head2->val; node = new ListNode(carry % 10); carry /= 10; pre_node->next = node; pre_node = node; head1 = head1->next; head2 = head2->next; } while (head1) { carry += head1->val; node = new ListNode(carry % 10); carry /= 10; pre_node->next = node; pre_node = node; head1 = head1->next; } while (head2) { carry += head2->val; node = new ListNode(carry % 10); carry /= 10; pre_node->next = node; pre_node = node; head2 = head2->next; } if (carry != 0) { node = new ListNode(carry % 10); pre_node->next = node; } // Reverse head1 and head2 reverse(orig_head1); reverse(orig_head2); // pseudo_head.next is the real head return reverse(pseudo_head.next); }
2. 查找最长非重复字符创的长度
#include <cmath> #include <iostream> #include <iomanip> #include <string> using namespace std; // The string pstr points to only contain 0~9 and a~z // Return the length of the longest non repeat characters // // E.g. // pstr = aefgsasdw // ^ ^ // The longest non repeat characters is "aefgs", so it should return 5 // int longest_non_repeat_characters(const char *pstr) { int index[256]; for (int iii = 0; iii < sizeof(index) / sizeof(int); iii++) index[iii] = -1; int ans = 0; int start = 0, cnt_pos = 0, end, len; const char *str = pstr; while (*str) { if (index[*str] != -1) { ans = max(ans, cnt_pos - start); end = index[*str]; // Update start to end inclusive for (int iii = start; iii <= end; iii++) index[ pstr[iii] ] = -1; start = end + 1; } index[*str] = cnt_pos++; str++; } ans = max(ans, cnt_pos - start); return ans; } int main() { const struct TestCase { const char *str; int ret; } test_cases[] = { { "", 0 }, { "abc", 3 }, { "abca", 3 }, { "xyzafegsahkbacbst", 8 }, }; for (int iii = 0; iii < sizeof(test_cases) / sizeof(TestCase); iii++) { const TestCase &tc = test_cases[iii]; if (tc.ret != longest_non_repeat_characters(tc.str)) { cout << "Case #" << iii << ": FAILED" << endl; } } return 0; }
作者:loverszhaokai
出处:http://www.cnblogs.com/lovers
本文采用知识共享署名-非商业性使用-相同方式共享 2.5 中国大陆许可协议进行许可,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。