您的位置:首页 > 其它

Restore IP Addresses & Sort List & Reorder List

2014-07-27 13:57 411 查看
(1) Restore IP Addresses

dfs, 几点注意的地方[1]:

1. 在验证字符串是否是数字的时候,要注意0的情况,001,010,03都是非法的。所以,如果第一位取出来是0,那么我们就判断字符串是否是"0",不是的情况都是非法的。

2. 取字符串的时候,注意位数不够的问题,不仅<4, 而且<s.length()。

class Solution {
private:
bool isValid(string s){
if(s[0]=='0')
return s=="0";
int num=atoi(s.c_str());
return num<=255 && num>0;
}

void dfs(string s,string tmp, vector<string> &ret,int dep) {

if(dep==3 && isValid(s))
{
ret.push_back(tmp+s);
return;
}

for(int i=1; i<4 && i<s.size(); i++)
{
string sub=s.substr(0,i);
if(isValid(sub))
dfs(s.substr(i,s.size()-i),tmp+sub+'.',ret,dep+1);
}
}

public:
vector<string> restoreIpAddresses(string s) {
vector<string> ret;

if(s.size()<4 || s.size()>12)
return ret;

dfs(s,"",ret,0);
return ret;
}
};

(2) Sort List
nlogn的排序有快速排序、归并排序、堆排序。双向链表用快排比较适合,堆排序也可以用于链表,单向链表适合用归并排序。以下是用归并排序的代码[2]:

class Solution {
private:
ListNode *mergeSort(ListNode *a,ListNode *b) {
if(!a) return b;
if(!b) return a;

ListNode *c,*cur;

if(a->val < b->val)
{ c=a; a=a->next;}
else {c=b; b=b->next;}
cur=c;

while(a && b)
{
if(a->val < b->val)
{
cur->next=a;
a=a->next;
}
else
{
cur->next=b;
b=b->next;
}
cur=cur->next;
}

if(a)
cur->next=a;
else
cur->next=b;

return c;
}

public:
ListNode *sortList(ListNode *head) {
if(!head || !head->next)
return head;

ListNode *fast=head,*slow=head;

while(fast->next && fast->next->next)
{
slow=slow->next;
fast=fast->next->next;
}
fast=slow;
slow=slow->next;
fast->next=NULL;

fast=sortList(head);
slow=sortList(slow);

return mergeSort(fast,slow);
}
};

(3) Reorder List 
把整个链表划分成2个等长的子链表,如果原链表长度为奇数,那么第一个子链表的长度多1,然后翻转第二个子链表,最后将两个子链表元素逐个轮流合并。

class Solution {
private:
ListNode *reverseList(ListNode *l) {
if(l->next==NULL)
return l;
ListNode *pre=l,*cur=l->next;
while(cur!=NULL)
{
ListNode* tmp=cur->next;
cur->next=pre;
pre=cur;
cur=tmp;
}
l->next=NULL;
return pre;
}

ListNode *mergeList(ListNode *a, ListNode *b)
{
ListNode *c=a,*cur;
a=a->next;
cur=c;
while(a!=NULL && b!=NULL)
{
cur->next=b;
b=b->next;
cur=cur->next;
cur->next=a;
a=a->next;
cur=cur->next;
}
if(b!=NULL)
cur->next=b;
return c;
}

public:
void reorderList(ListNode *head) {
if(head==NULL || head->next==NULL || head->next->next==NULL)
return;

ListNode *slow=head,*fast=head;

while(fast->next!=NULL && fast->next->next!=NULL)
{
slow=slow->next;
fast=fast->next->next;
}

fast=slow->next;
slow->next=NULL;
fast=reverseList(fast);
head=mergeList(head,fast);
}
};

参考:

[1] http://blog.csdn.net/u011095253/article/details/9158449

[2] http://www.cnblogs.com/TenosDoIt/p/3434550.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: