用双向链表解决左旋转字符串的问题

在这里插入图片描述
标准解法应该是这样:

链接: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;
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值