
标准解法应该是这样:
链接:https://www.nowcoder.com/questionTerminal/12d959b108cb42b1ab72cef4d36af5ec?answerType=1&f=discussion
来源:牛客网
class Solution {
public:
string LeftRotateString(string str, int n) {
if (n > str.size()) return str;
string ret = "";
for (int i=n; i<str.size(); ++i)
ret += str[i];
for (int i=0; i<n; ++i)
ret += str[i];
return ret;
}
};
但是自己用双向链表解决了这题,感觉自己饶了一大圈,其实不用这么麻烦。
但是好歹也是写了,也是一种解法,就先放在这里吧
说明:
因为移动的时候是一个字母一个字母的左移,所以必然会有一个字母在移动的时候给覆盖了。temp就是用来先存储这个被覆盖的字母,在后序插入用的。
例如,字符串顺序为 abcXYZdef
一次移动后:bcXYZdeff
二次移动:cXYZdeffb
三次移动:XYZdeffbc
最后把temp插入回去,构成结果:XYZdefabc
一下是用双向链表实现的代码:
using System.Collections.Generic;
class CircleNode//双向链表类
{
public char letter;
public CircleNode pre;
public CircleNode next;
}
class Solution
{
{
CircleNode head=new CircleNode();
head.letter=str[0];
head.pre=null;
head.next=null;
CircleNode end=head;//end节点始终指向链表的末尾
for(int i=1;i<str.Length;i++)
{
CircleNode node=new CircleNode();
node.letter=str[i];
node.next=null;
node.pre=end;
end.next=node;
end=end.next;
}
end.next=head;//将双向链表首尾连接起来
head.pre=end;
return head;
}
public string LeftRotateString(string str, int n)
{
if(str.Length==0)
{
return str;//这个是应付测试用例的
}
CircleNode head=InitCircleNode(str);//初始化,将str全部转移到双向链表中
CircleNode current=head;
char temp=head.letter;//temp存贮第一个会被覆盖的值,也就是head的值
for(int i=0;i<n;i++)//向左移几位,就要整体移动几次
{
for(int j=0;j<str.Length-1;j++)//整个链表的值开始发生移动,每次移动一个节点的值到前一节点
{
current=current.next;
current.pre.letter=current.letter;
}
}
current.letter=temp;//全部移动完成后,current此时指向第一个被覆盖的值要插入的位置
string ret="";
current=head;
for(int i=0;i<str.Length;i++)
{
ret+=current.letter;
current=current.next;
}
return ret;
}
}

被折叠的 条评论
为什么被折叠?



