百度面试题:字符串翻转代码

2015-05-24 0 316
百度面试题:字符串翻转代码

给定一个字符串,比如“abcdef”,要求写一个函数,将字符串翻转成“defabc”,或者翻转成“efabcd”,字串位数要求是可变的。

此题还是2011年考研数据结构压轴大题,在百度面前也就是一面第一题。可见百度一斑。

解法是将字符串进行3次翻转,第一次翻转整个字符串,第二次跟第三次翻转部分字符串。

#include<stdio.h>
 
void swap(char *str,int n)
{
    char temp;
    char *p,*q;
    p = str;
    q = str + n - 1;
    while(p < q)
    {
        temp = *p;
        *p = *q;
        *q = temp;
        p++;
        q--;   
    }
}
void reserve(char *str,int n)
{
    swap(str,strlen(str));
    swap(str,n);
    swap(str+n,strlen(str)-n); 
}
int main(int argc,char *argv[])
{
    char str[10] = "abcdef";
    printf("%s\n",str);
    reserve(str,3);        //3是翻转的位数
    printf("%s\n",str);
    return 0;
}

遇见资源网 c/c++ 百度面试题:字符串翻转代码 http://www.ox520.com/10098.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务