zoukankan      html  css  js  c++  java
  • 面试题_旋转字符串

    题目:定义字符串的左旋转操作:把字符串前面的若干个字符移动到字符串的尾部。如把字符串abcdef左旋转2位得到字符串cdefab。请实现字符串左旋转的函数。要求时间对长度为n的字符串操作的复杂度为O(n),辅助内存为O(1)

    思路:将字符串看做AB两部分,将A反转,再将B反转,最后将反转后的A+反转后的B一起反转就OK了。

    #include<iostream>
    #include
    <assert.h>
    using namespace std;
    const int MAX=100;
    //反转从start到end的字符串s
    void Reversal(int start,int end,char *s)
    {
    assert(s
    !=NULL);
    int halfLength=(end+1+start)/2;
    for(int i=start;i<halfLength;i++)
    {
    char temp=s[i];
    s[i]
    =s[end+start-i];
    s[end
    +start-i]=temp;
    }
    }
    int main()
    {
    char str[MAX];
    int leftLength,i,j,length;
    while(cin>>str>>leftLength)
    {
    length
    =strlen(str);
    if(leftLength<=0||leftLength>=length) break;
    Reversal(
    0,leftLength-1,str);
    Reversal(leftLength,length
    -1,str);
    Reversal(
    0,length-1,str);
    cout
    <<str<<endl;
    }
    return 0;
    }

  • 相关阅读:
    结构体比较
    不定长参数列表用法
    接口
    字符串数据类型
    *和**的打包和解包
    python类常用装饰器
    继承的实现
    map用法
    包的导入和init函数
    协程
  • 原文地址:https://www.cnblogs.com/coser/p/1978423.html
Copyright © 2011-2022 走看看