给定一个字符串,要求把字符串前面的若干个字符移动到字符串的尾部,如把字符串“abcdef”前面的2个字符'a'和'b'移动到字符串的尾部,使得原字符串变成字符串“cdefab”。请写一个函数完成此功能,要求对长度为n的字符串操作的时间复杂度为 O(n),空间复杂度为 O(1)。
初看此题,可能最先想到的方法是按照题目所要求的,把需要移动的字符一个一个地移动到字符串的尾部,如此我们可以实现一个函数LeftShiftOne(char* s, int n) ,以完成移动一个字符到字符串尾部的功能,代码如下所示:
下面,我们来分析一下这种方法的时间复杂度和空间复杂度。
针对长度为n的字符串来说,假设需要移动m个字符到字符串的尾部,那么总共需要 mn 次操作,同时设立一个变量保存第一个字符,如此,时间复杂度为O(m n),空间复杂度为O(1),空间复杂度符合题目要求,但时间复杂度不符合,所以,我们得需要寻找其他更好的办法来降低时间复杂度。
c语言版:
#include <stdio.h>
#include <string.h>
void LeftShiftOne(char* s, int n)
{
char t = s[0]; //保存第一个字符
for (int i = 1; i < n; i++)
{
s[i - 1] = s[i];
}
s[n - 1] = t;
}
//
void LeftRotateString(char* s, int n, int m)
{
while (m--)
{
LeftShiftOne(s, n);
}
}
int main(){
char f[]="hello world";//必须用数组形式
int e=strlen(f);
printf("%d\n",e);
LeftRotateString(f,e,2);
puts(f);
return 0;
}
go版:
package main
import(
"fmt"
)
func main(){
s :=[]byte("hello world")
LeftRotateString(s,len(s),2)
fmt.Println(string(s))
}
func LeftShiftOne(s []byte,n int){
t:=s[0]
for i:=1;i<n;i++{
s[i-1]=s[i]
}
s[n-1]=t
}
func LeftRotateString(s []byte,n int,m int){
for{
m=m-1
if m<0{
break
}
LeftShiftOne(s, n)
}
}
php版:
<?php
function LeftShiftOne(&$str,$n){
$t=$str[0];
for($i=1;$i<$n;$i++){
$str[$i-1]=$str[$i];
}
$str[$n-1]=$t;
}
function LeftRotateString(&$str,$n,$m){
while($m--){
LeftShiftOne($str,$n);
}
}
$str="hello world";
LeftRotateString($str,strlen($str),2);
echo $str;