2015-09-09 [一点资讯]--数据抓取和处理工程师--1面

1. 实现链表加法

// 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;

}

return pre_node;
}

{
if (head1 == NULL && head2 == NULL)
return NULL;

ListNode *pre_node = &pseudo_head;
ListNode *node;
int carry = 0;

node = new ListNode(carry % 10);

carry /= 10;
pre_node->next = node;
pre_node = node;

}

node = new ListNode(carry % 10);

carry /= 10;
pre_node->next = node;
pre_node = node;

}

node = new ListNode(carry % 10);

carry /= 10;
pre_node->next = node;
pre_node = node;

}

if (carry != 0) {

node = new ListNode(carry % 10);
pre_node->next = node;
}

}

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;
}

posted @ 2015-09-10 14:06 loverszhaokai 阅读(...) 评论(...) 编辑 收藏