《剑指offer》-左旋转字符串

汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!

基本的字符串子串和拼接。C++里的string的substr(int start_index, int count) 起始索引和数量。

这种题目就喜欢在细节上挖坑,比如字符串长度为0,你怎么搞?要能够应对这种情况。过分专注细节,这样的任务应当交给机器去做。

class Solution {
public:
	string LeftRotateString(string str, int n){
		int len = str.length();
		if (len == 0){
			return "";
		}
		n = n%len;
		string result = str.substr(n, len - n) + str.substr(0, n);
		return result;
	}
};
原文地址:https://www.cnblogs.com/zjutzz/p/6616407.html