[置顶] 循环右移字符串简易探讨

#include <iostream>
#include <cstdlib>
#include <string>
#include <queue>

using namespace std;
/*
 *设计一个算法,把一个含有N个元素的数组循环右移K位,要求时间复杂度为O(N)
*/

/*
 * 方案一:将数组以队列存储,循环右移k位,相当于循环左移N-K位
 * 对于队列而言,循环左移一位,相当于取出队头元素然后插入队尾
*/
class Solution {
private:
	string str;     // 源字符串,由键盘输入
	string result;  // 转换后的字符串
	queue<char>q;   // 辅助队列
public:
	Solution() {
		cin>>str;
		string::iterator it;
		/*
		 * 将输入字符串转换为队列
		*/
		for(it = str.begin();it!= str.end();it++) {
			q.push(*it);   // 将元素插入队尾
		}
	}
	void JustDoIt(int k) {
		int i;
		char t;
		int n = q.size();  // 取出队列元素个数
		/*
		 * 参数判断
		*/
		if(k < 0) {
			cerr<<"参数错误!"<<endl;
			exit(1);
		}
		/*
		 * 当k > N时,循环右移K位,相当与循环右移K%N位
		*/
		k %= n;
		for(i = 1;i <= n - k;i++) {
			t = q.front(); // 取出对头元素 
			q.pop();       // 弹出对头元素(队列头部出,尾部进)  
			q.push(t);
		}
		/*
		 * 生成结果字符串
		*/
		for(i = 1;i <= n;i++) {
			t = q.front();
			q.pop();
			result += t;
		}
	}
	void show() const {
		cout<<result<<endl;
	}
};
void main() {
	Solution s;
	s.JustDoIt(4);
	s.show();
}


#include <iostream>
#include <cstdlib>
#include <string>
#include <queue>

using namespace std;
/*
 *设计一个算法,把一个含有N个元素的数组循环右移K位,要求时间复杂度为O(N)
*/

/*
 * 方案二:将数组以字符串存储,使用转置法解决
 * 假设字符串为XY,Y是要循环右移的子串,移动后结果应该是YX
 * 那么 (YX) = (XTYT)T
*/
class Solution {
private:
	string str;     // 源字符串,由键盘输入
	string result;  // 转换后的字符串
public:
	Solution() {
		cin>>str;
	}
	/*
	 * 逆转从指针i到指针j的字符串s
	*/
	void swap(string &s, int i, int j) {
		char t;
		while(i < j) {
			t = s[i];
			s[i] = s[j];
			s[j] = t;
			i++;
			j--;
		}
	}
	void JustDoIt(int k) {
		int n = str.size();
		/*
		 * 参数判断
		*/
		if(k < 0) {
			cerr<<"参数错误!"<<endl;
			exit(1);
		}
		/*
		 * 当k > N时,循环右移K位,相当与循环右移K%N位
		*/
		k %= n;
		result = str;

		swap(result, 0, n - k - 1);
		swap(result, n - k, n -1);
		swap(result, 0, n - 1);
	}
	void show() const {
		cout<<result<<endl;
	}
};
void main() {
	Solution s;
	s.JustDoIt(4);
	s.show();
}


测试:



原文地址:https://www.cnblogs.com/pangblog/p/3265344.html