点:技巧性问题
题意:如字符串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;
}