来自 The-Art-Of-Programming-By-July 中的1.1。
原始问题:
给定一个字符串,要求把字符串前面的若干个字符移动到字符串的尾部,如把字符串“abcdef”前面的2个字符'a'和'b'移动到字符串的尾部,使得原字符串变成字符串“cdefab”。请写一个函数完成此功能,要求对长度为n的字符串操作的时间复杂度为 O(n),空间复杂度为 O(1)。
解法:三步反转法。
void ReverseString(char *s, int from, int to)
{
while(from<to)
{
char t=s[from];
s[from]=s[to];
s[to]=t;
from++;
to--;
}
}
void LeftRotateString(char *s, int n, int m)
{
m%=n;
ReverseString(s, 0, m-1);
ReverseString(s, m, n-1);
ReverseString(s, 0, n-1);
}
举一反三:
1. 链表翻转。给出一个链表和一个数k,比如,链表为1→2→3→4→5→6,k=2,则翻转后2→1→6→5→4→3,若k=3,翻转后3→2→1→6→5→4,若k=4,翻转后4→3→2→1→6→5,用程序实现。
struct node
{
int val;
struct node *next;
};
struct node *ReverseList(struct node *l, struct node *p_from, struct node *p_to)
{
struct node *head;
struct node *tail;
struct node *q;
if(p_from==l)
{
//cout<<"head"<<endl;
head=new struct node;
head->next=p_from;
}
else
{
//cout<<"not_head"<<endl;
head=l;
while(head->next!=p_from)
head=head->next;
}
tail=p_to->next;
while(p_from->next!=tail)
{
q=p_from->next;
p_from->next=q->next;
q->next=head->next;
head->next=q;
}
if(l==p_from)
return head->next;
else
return l;
}
struct node *func(struct node *l, int n, int k)
{
assert(l!=NULL);
assert(k>=0&&k<=n);
struct node *tmp=l;
map<int,struct node *> p_map;
int index=1;
while(tmp!=NULL)
{
p_map[index]=tmp;
index++;
tmp=tmp->next;
}
if(k==0||k==n)
return ReverseList(l, p_map[1], p_map[n]);
struct node *re1=ReverseList(l, p_map[1], p_map[k]);
struct node *re2=ReverseList(re1, p_map[k+1], p_map[n]);
return re2;
}
ReverseList函数可以反转链表l中任意p_from指针和p_to指针中间的节点。思路参见链表反转的解法二。在这里,使用了两个伪指针,分别是head和tail。并对于p_from指针和l指针是否相等进行讨论。
func函数中使用了map对链表中的节点指针和节点具体的位置进行索引,通过索引可以方便找到节点具体位置的指针。当k等于0或者k等于链表长度的时候分为一种情况。
2. 单词翻转。输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变,句子中单词以空格符隔开。为简单起见,标点符号和普通字母一样处理。例如,输入“I am a student.”,则输出“student. a am I”。
void ReverseString(char *s, int from, int to)
{
while(from<to)
{
char t=s[from];
s[from]=s[to];
s[to]=t;
from++;
to--;
}
}
void RevergeStringWord(char *s, int n)
{
int i_blank, pre_blank;
pre_blank=-1;
for(int i=0;i<n;i++)
{
if(s[i]==' ')
{
i_blank=i;
ReverseString(s, pre_blank+1, i_blank-1);
pre_blank=i_blank;
}
}
ReverseString(s, i_blank+1, n-1);
ReverseString(s, 0, n-1);
}
思路是根据空格分段反转,再进行整体反转。