其他分享
首页 > 其他分享> > 每日一题 0202

每日一题 0202

作者:互联网

(2022.02.02)每日一题 反转单词前缀

简单的题,第一想法双指针模拟。

一个指针去查找字符串中的字符,另一个指针始终指向字符串首,当查找指针找到后,通过交换两个指针指向的字符,并且指针范围收缩,直至右指针小于左指针退出循环。

class Solution {
public:
    string reversePrefix(string word, char ch) {
        char* pfinder = &word[0];
        char* pchanger = &word[0];
        //通过ASCII码是否相同来判断是否是同一个字母
        while((*pfinder - ch )!=0){
            //根据字符串结尾都会由\0表示结尾,来判断字符串中不存在字符。
            if(*pfinder == '\0'){
                return word;
            }
            ++pfinder;
        }
        //简单的交换
        while(pfinder > pchanger){
            char temp = *pfinder;
            *pfinder = *pchanger;
            *pchanger = temp;
            --pfinder;
            ++pchanger;
        }
        return word;
    }
};



//official
class Solution {
public:
    string reversePrefix(string word, char ch) {
        int index = word.find(ch);
        //string::npos是一个特殊值,用于匹配没有查找到的结果,即说明查找没有匹配的结果。
        if (index != string::npos) {
            //reverse反转[begin,last)范围内的字符串
            reverse(word.begin(), word.begin() + index + 1);
        }
        return word;
    }
};

标签:pchanger,word,string,每日,pfinder,char,0202,指针
来源: https://www.cnblogs.com/kusola9808/p/15860624.html