字符串左右旋

点:技巧性问题


题意:如字符串1234567890,希望旋转为5678901234

常见面试题


思路:还是那句话,这类题,绝对是各种技巧去解决,递归、循环、双向相遇、快慢指针、各种其他技巧。。。。。

具体到本题,直接交换的话实现起来甚至还非常麻烦,比如5不能和1交换,因为最后两个字符90怎么办,这种情况程序很难描述。

最好的办法是1234能够和567890整体换位,而不是断断续续的写一堆if else,

一个很重要的思路是"负负为正",1234自己互相交换顺序是4321,567890自己交换顺序是098765,组成的字符串是4321098765,然后再把这个新的字符串倒过来,就是5678901234了。确实有一些字符串问题,是以一些技巧性的思路解决。


代码:

#include <iostream>
#include <string>


void swap (std::string &res, int st, int ed) {
    if (st != ed) {
        char ch = res[st];
        res[st] = res[ed];
        res[ed] = ch;
    }
}

void rotate (std::string &res, int st, int ed) {
    while (st < ed) {
        swap(res, st, ed);
        ++st;
        --ed;
    }
}

std::string str_rotate (const std::string &raw, int idx) {
    std::string res = raw;
    rotate(res, 0, idx);
    rotate(res, idx + 1, res.length() - 1);
    rotate(res, 0, res.length() - 1);
    return res;
}

int main () {
    std::string raw = "1234567890";
    int i = 3;
    std::cout << str_rotate(raw, 3) << std::endl;
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值