[剑指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!=''){
        ++end;
    }
    reverse(beg, end-1);
    
    end=s;
    while(*end!=''){
        if(*beg==' '){
            ++beg;
            ++end;
        }
        else if(*end==' '||*end==''){
            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;
}
原文地址:https://www.cnblogs.com/coding-gaga/p/10452476.html