面试题 42 翻转

(1)经典面试题: 翻转句子中的单词,并将单词的字母顺序翻转, 标点符号和字母一样处理

复制代码
void Reverse(char *begin, char *end){

    if(begin == NULL || end == NULL)
        return ;
    while(begin < end){
        char tp = *begin;
        *begin = *end;
        *end = tp;
        begin++;
        end--;
    }
}

char * ReverseSentence(char *sentence){

    if(sentence == NULL)
        return NULL;
    char *end = sentence;
    while(*end != ‘\0' )end++;
    end--;
    Reverse(sentence, end);
    char *begin = sentence;
    end = sentence;
    while(begin != '\0'){
        while(*end != ' ' && *end != '\0') end++;
        Reverse(begin,end-1);
        while(*end == ' ') end++;
        begin = end;
    }
    return sebtence;
}
复制代码

(2)左旋若干个字符

复制代码
char * LeftRotateString(char *str, int n){

    //if(str == NULL) return str;
    int len = strlen(str);
    if(str == NULL || n <0 || n > len)
        return str;
    
    char *firstbegin = str;
    char *firstend = str + n-1;
    char * secondbegin = str + n;
    char * secondend = str +len -1;
    Reverse(firstbegin, firstend);
    Reverse(secondbegin, secondend);
    Reverse(firstbegin, secondend);
    
    return str;
    
}
复制代码

 

 

posted @   冰点猎手  阅读(138)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示