LintCode 8. Roatate String
Description
Given a string(Given in the way of char array) and an offset, rotate the string by offset in place. (rotate from left to right)
offset >= 0
the length of str >= 0
给定一个字符串(以字符数组的形式给出)和一个偏移量,根据偏移量原地旋转字符串(从左向右旋转)
Example
Input: str=“abcdefg”, offset = 3
Output: str = “efgabcd”
Explanation: Note that it is rotated in place, that is, after str is rotated, it becomes “efgabcd”.
Input: str=“abcdefg”, offset = 0
Output: str = “abcdefg”
Explanation: Note that it is rotated in place, that is, after str is rotated, it becomes “abcdefg”.
Input: str=“abcdefg”, offset = 1
Output: str = “gabcdef”
Explanation: Note that it is rotated in place, that is, after str is rotated, it becomes “gabcdef”.
Input: str=“abcdefg”, offset =2
Output: str = “fgabcde”
Explanation: Note that it is rotated in place, that is, after str is rotated, it becomes “fgabcde”.
Input: str=“abcdefg”, offset = 10
Output: str = “efgabcd”
Explanation: Note that it is rotated in place, that is, after str is rotated, it becomes “efgabcd”.
Challenge
Rotate in-place with O(1) extra memory.
Submission
1. 使用substr函数
class Solution {
public:
/**
* @param str: An array of char
* @param offset: An integer
* @return: nothing
*/
void rotateString(string &str, int offset) {
// write your code here
if (str.size() == 0){
return;
}
offset = offset % str.size();
str = str.substr(str.size() - offset, offset)
+ str.substr(0, str.size() - offset);
}
};
2. 两两交换的方式
2.1 穷举法
class Solution {
public:
/**
* @param str: An array of char
* @param offset: An integer
* @return: nothing
*/
void rotateString(string &str, int offset) {
// write your code here
int temple ; //替换的值
int cot = 0; // 计数器
int len = str.size();
// 按顺序依次进行交换,offset表示交换的轮数
for(cot; cot < offset; cot++){
temple = str[len - 1];
for(int i = len - 1; i > 0; i--){
str[i] = str[i - 1];
}
str[0] = temple;
}
}
};
这种方式得到的结果的算法复杂度为O(KN),若交换的次数过多(即K值大),计算量就超出限制的,这里的结果是:Time Limit Exceeded
2.2 改进的穷举法
交换的次数过大,可以考虑(K%N)的情况,交换N次不是等于不变嘛。Accepted
class Solution {
public:
/**
* @param str: An array of char
* @param offset: An integer
* @return: nothing
*/
void rotateString(string &str, int offset) {
// write your code here
int temple ; //替换的值
int cot = 0; // 计数器
int len = str.size();
if(len){
offset = offset % len;
}
for(cot; cot < offset; cot++){
temple = str[len - 1];
for(int i = len - 1; i > 0; i--){
str[i] = str[i - 1];
}
str[0] = temple;
}
}
};
2.3 直接交换法
待更新…