[日常] 算法-旋转字符串-暴力移位法
2023-02-18 15:47:11 时间
题目描述
给定一个字符串,要求把字符串前面的若干个字符移动到字符串的尾部,如把字符串“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;
相关文章
- [日常] windows下使用vscode配合xebug调试php脚本
- [PHP] cli环境下php设置进程名字
- [PHP]解决 Call-time pass-by-reference has been removed
- [PHP]解决PHP Call to undefined function ldap_connect()
- [Nginx] Nginx配置PHP应用传递PATH_INFO变量
- [PHP]解决PHP Fatal error: Call to undefined function mcrypt_get_iv_size()
- [CentOS] centos下安装最新稳定版nginx
- [CentOS]查看centos的发行版本情况
- [MySQL]创建用户并指定某一数据库权限
- [PHP] 安装memcached扩展
- [http]301和302的区别
- [MySQL]简单理解并发下的CAS比较交换和ABA问题
- [前端]使用meta控制双核浏览器默认使用webkit/chrome内核
- [PHP] pmap可以查看进程占用内存的详细情况
- [PHP] 解决php中上传大文件的错误
- [日常]GB2312 GBK GB18030的区别和演进过程
- [PHP] 循环查看php-fpm的内存占用情况
- [日常]中文字符串比较大小的方式
- [日常]win10解除网速限制
- [日常]解决win10没有组策略问题