字符串逆转问题

问题描述: 
长度为n的字符串,在第 i 的位置处向左旋转或者向右旋转。比如字符串abcdefgh 长度n为8 ,若将该字符串在i=3的位置处,向左旋转则得到字符串defghabc 。问题要求:时间复杂度要和n成正比,内存几十字节。
问题解决方法:
数学基础   即将矩阵 AB  变为BA 。  
AB---> A'B--->A'B'------>(A'B')'--------->BA  。  其中 '   表示矩阵的转置。
解决方法:  
将abc 看做A ,defgh 看做 B 
具体算法:
(1)        abcdefgh----->  cbadefgh                      reverse(0 , i - 1)
(2)        cbadefgh------>  cbahgfed                     reverse( i  ,   n - 1)
 (3)          cbahgfed ------> defghabc                     reverse(0 , n - 1)
 
总结:

通过上述(1),(2),(3) 即完成了字符串转置 。每一个reverse() 函数的时间复杂度均为o(n) ,空间复杂度只利用了一个临时变量,满足上述要求。

#include <iostream>
#include 
<cstring>
using namespace std ;
const int SIZE   = 40 ;
   
   
void reverse(char* a , int begin , int end)
   
{
     
int i = begin , j = end ;
     
int times = (j - i + 1/ 2 ;
     
int temp ;
     
while(times > 0)
     
{
       temp 
= a[i] ;          
       a[i
++= a[j] ;
       a[j
--= temp ; 
        times
-- ;            
     }

     
     
     
   }

   
   

 
int main()
 
{  
    
int i ;
    
char str [SIZE] ;
    cout
<<"input str:"
    cin
>>str ;
    
    cout
<<"input i:" ;
    cin
>>i ;
    
     reverse(str , 
0 , i - 1) ;
     reverse(str , i , strlen(str) 
- 1) ;
     reverse(str , 
0 , strlen(str) - 1) ;
     
for(int i = 0 ; i <  strlen(str) ; i++)
       cout
<<str[i];
     
     cin.
get();
    
return 0 ;    
 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值