0
点赞
收藏
分享

微信扫一扫

LeetCode 题解随笔:字符串篇

40dba2f2a596 2022-04-30 阅读 48

一、双指针法相关

344.反转字符串

void reverseString(vector<char>& s) {
        int front = 0;
        int back = s.size() - 1;
        while (front < back) {
            char temp = s[back];
            s[back] = s[front];
            s[front] = temp;
            front++;
            back--;
        }
    }

这里提供一个方便查看vector结果的函数:

template<typename T>
void MyPrint(vector<T> v) {
    for (auto it = v.begin(); it != v.end(); it++) {
        cout << *it << " ";
    }
    cout << endl;
}

541. 反转字符串II

void reverseString(string& s, int front, int back) {
        while (front < back) {
            char temp = s[back];
            s[back] = s[front];
            s[front] = temp;
            front++;
            back--;
        }
    }

string reverseStr(string s, int k) {
        int start = 0;
        int count = s.size();
        while (start < s.size())
        {
            int left = start;
            if (count < k) { 
                int right = start + count - 1;
                reverseString(s, left, right);
                return s;
            }
            else if (count >= k && count < 2 * k) {
                int right = start + k - 1;
                reverseString(s, left, right);
                return s;
            }
            else {
                int right = start + k - 1;
                reverseString(s, left, right);
                start += 2 * k;
                count -= 2 * k;
            }
        }
        return s;
    }

与上一题类似,直接进行行为模拟即可。当考察内容不是直接调用库函数就能完成时,可以采用库函数。例如本题中的反转可以利用reverse实现。

另外,当需要固定规律一段一段去处理字符串的时候,要想想在for循环的表达式上做做文章。本题可以利用下式进行循环。

for (int i = 0; i < s.size(); i += (2 * k))

二、字符串填充替换

剑指Offer 05.替换空格

string replaceSpace(string s) {
        //首先统计空格字符个数,对字符串进行预扩容
        int count = 0;
        for (auto i : s) {
            if (i == ' ') {
                count++;
            }
        }
        if (count == 0) return s;
        s.resize(s.size() + 2 * count);
        int right = s.size() - 1;
        int left = right - 2 * count;
        //从后向前修改字符串
        while (left >= 0) {
            if (s[left] == ' ') {
                s.replace(right - 2, 3, "%20");
                left--;
                right -= 3;
            }
            else {
                s[right--] = s[left--];
            }
        }
        return s;
    }

数组填充类的问题,可以预先给数组扩容到填充后的大小,再从后向前进行操作

举报

相关推荐

字符串题解

0 条评论