[剑指Offer]58-翻转字符串

题目一 翻转单词顺序

题意

输入一个英文句子,翻转句子中的单词的顺序,但单词内自负的顺序不变。标点符号和普通字母一样处理。
例:
输入:"I am a student."
输出:“student. a am I”

思路

reverse实现翻转,则第一步翻转整个句子,第二步翻转每个单词。

代码

#include <iostream>
using namespace std;

void reverse(char* beg,char* end){
    if(beg==nullptr||end==nullptr){
        return;
    }
    while(beg<end){
        char temp=*beg;
        *beg=*end;
        *end=temp;
        
        ++beg;
        --end;
    }
}

char* reverseSentence(char* s){
    char* beg=s;
    char* end=s;
    while(*end!='\0'){
        ++end;
    }
    reverse(beg, end-1);
    
    end=s;
    while(*end!='\0'){
        if(*beg==' '){
            ++beg;
            ++end;
        }
        else if(*end==' '||*end=='\0'){
            reverse(beg, end-1);
            beg=++end;
        }
        else{
            ++end;
        }
    }
    return s;
}

int main(int argc, const char * argv[]) {
    char s[]="I am a student.";
//    char s[]=" ";
    reverseSentence(s);
    cout<<s<<endl;
    return 0;
}

题目二 左旋转字符串

题意

把字符串前面的若干个(n)字符转移到字符串的尾部。
例:
输入:"coolday"和n=4
输出:“daycool”

思路

reverse实现翻转,第一步翻转整个句子,第二步翻转后n个字符组成的字符串,第三步翻转前面部分的字符串。
注意输入在合法范围,以及不用处理的情况。

其他

1 字符串处理:注意 一:输入空指针nullptr的特殊处理;二:避免内存访问越界问题。
2 关于strlen()和sizeof()
char* s[]="sunny";
strlen(s)==5
sizeof(s)/sizeof(char)==6

代码

#include <iostream>
#include <string>
using namespace std;

void reverse(char* beg,char* end){
    if(beg==nullptr||end==nullptr){
        return;
    }
    while(beg<end){
        char temp=*beg;
        *beg=*end;
        *end=temp;
        
        ++beg;
        --end;
    }
}

void leftRotate(char* s,int rotateLen){
    size_t len=strlen(s);
    
    if(s!=nullptr&&rotateLen>0&&rotateLen<len){//输入合法;当rotateLen=len时不用处理
        char* beg=s;
        char* end=s+len-1;
        reverse(beg, end);
        
        beg=end-rotateLen+1;
        reverse(beg,end);
        
        end=beg-1;
        beg=s;
        reverse(beg,end);
    }
}

int main(){
    char s[]="coolday";
    int rotateLen=4;
//    char s[]="c";
//    int rotateLen=1;
    leftRotate(s,rotateLen);
    cout<<s<<endl;
    return 0;
}

posted on   coding_gaga  阅读(165)  评论(0编辑  收藏  举报

编辑推荐:
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
阅读排行:
· “你见过凌晨四点的洛杉矶吗?”--《我们为什么要睡觉》
· 编程神器Trae:当我用上后,才知道自己的创造力被低估了多少
· C# 从零开始使用Layui.Wpf库开发WPF客户端
· C#/.NET/.NET Core技术前沿周刊 | 第 31 期(2025年3.17-3.23)
· 接口重试的7种常用方案!
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示