leetcode刷题记录36(2023-5-19)【文本左右对齐(字符串运算) | 两数之和 II - 输入有序数组(双指针) | 长度最小的子数组(滑动窗口) | 串联所有单词的子串(滑动窗口)】

68. 文本左右对齐

给定一个单词数组 words 和一个长度 maxWidth ,重新排版单词,使其成为每行恰好有 maxWidth 个字符,且左右两端对齐的文本。

你应该使用 “贪心算法” 来放置给定的单词;也就是说,尽可能多地往每行中放置单词。必要时可用空格 ’ ’ 填充,使得每行恰好有 maxWidth 个字符。

要求尽可能均匀分配单词间的空格数量。如果某一行单词间的空格不能均匀分配,则左侧放置的空格数要多于右侧的空格数。

文本的最后一行应为左对齐,且单词之间不插入额外的空格。

注意:

单词是指由非空格字符组成的字符序列。
每个单词的长度大于 0,小于等于 maxWidth。
输入单词数组 words 至少包含一个单词。

示例 1:

输入: words = [“This”, “is”, “an”, “example”, “of”, “text”, “justification.”], maxWidth = 16
输出:

[
   "This    is    an",
   "example  of text",
   "justification.  "
]

示例 2:

输入:words = [“What”,“must”,“be”,“acknowledgment”,“shall”,“be”], maxWidth = 16
输出:

[
  "What   must   be",
  "acknowledgment  ",
  "shall be        "
]

解释: 注意最后一行的格式应为 "shall be " 而不是 “shall be”,
因为最后一行应为左对齐,而不是左右两端对齐。
第二行同样为左对齐,这是因为这行只包含一个单词。
示例 3:

输入:words = [“Science”,“is”,“what”,“we”,“understand”,“well”,“enough”,“to”,“explain”,“to”,“a”,“computer.”,“Art”,“is”,“everything”,“else”,“we”,“do”],maxWidth = 20
输出:

[
  "Science  is  what we",
  "understand      well",
  "enough to explain to",
  "a  computer.  Art is",
  "everything  else  we",
  "do                  "
]

提示:

1 <= words.length <= 300
1 <= words[i].length <= 20
words[i] 由小写英文字母和符号组成
1 <= maxWidth <= 100
words[i].length <= maxWidth

主要思路就是一行一行的拼接,拼接完成后再拼下一行,循环往复:

#include <string>
#include <vector>
#include <iostream>

using namespace std;

class Solution
{
public:
    vector<string> fullJustify(vector<string> &words, int maxWidth)
    {
        int cur = 0, lastIdx = 0;
        vector<string> res;
        for (int i = 0; i < words.size(); i++)
        {

            if (cur + words[i].size() + (i - lastIdx) > maxWidth)
            {
                int numBlack = i - 1 > lastIdx ? (maxWidth - cur) / (i - 1 - lastIdx) : 0;
                int numMore = i - 1 > lastIdx ? (maxWidth - cur) % (i - 1 - lastIdx) : 0;
                // 拼接一行
                string newLine = words[lastIdx];
                for (int j = lastIdx + 1; j < i; j++)
                {
                    for (int k = 0; k < numBlack; k++)
                    {
                        newLine += " ";
                    }
                    if (j - lastIdx <= numMore)
                    {
                        newLine += " ";
                    }
                    newLine += words[j];
                }
                if (newLine.size() < maxWidth)
                {
                    int numExtra = maxWidth - newLine.size();
                    for (int m = 0; m < numExtra; m++)
                    {
                        newLine += " ";
                    }
                }
                res.push_back(newLine);
                // 更新变量
                cur = words[i].size();
                lastIdx = i;
            }
            else
            {
                cur += words[i].size();
            }
        }
        string lastLine = words[lastIdx];
        for (int i = lastIdx + 1; i < words.size(); i++)
        {
            lastLine += " ";
            lastLine += words[i];
        }
        while (lastLine.size() < maxWidth)
        {
            lastLine += " ";
        }
        res.push_back(lastLine);
        return res;
    }
};

int main()
{
    vector<string> vec = {"Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"};
    int maxWidth = 20;
    Solution sol;
    vector<string> res = sol.fullJustify(vec, maxWidth);
    for (int i = 0; i < res.size(); i++)
    {
        cout << res[i] << endl;
    }
}

167. 两数之和 II - 输入有序数组

给你一个下标从 1 开始的整数数组 numbers ,该数组已按 非递减顺序排列 ,请你从数组中找出满足相加之和等于目标数 target 的两个数。如果设这两个数分别是 numbers[index1] 和 numbers[index2] ,则 1 <= index1 < index2 <= numbers.length 。

以长度为 2 的整数数组 [index1, index2] 的形式返回这两个整数的下标 index1 和 index2。

你可以假设每个输入 只对应唯一的答案 ,而且你 不可以 重复使用相同的元素。

你所设计的解决方案必须只使用常量级的额外空间。

示例 1:

输入:numbers = [2,7,11,15], target = 9
输出:[1,2]
解释:2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。返回 [1, 2] 。

示例 2:

输入:numbers = [2,3,4], target = 6
输出:[1,3]
解释:2 与 4 之和等于目标数 6 。因此 index1 = 1, index2 = 3 。返回 [1, 3] 。

示例 3:

输入:numbers = [-1,0], target = -1
输出:[1,2]
解释:-1 与 0 之和等于目标数 -1 。因此 index1 = 1, index2 = 2 。返回 [1, 2] 。

提示:

  • 2 < = n u m b e r s . l e n g t h < = 3 ∗ 1 0 4 2 <= numbers.length <= 3 * 10^4 2<=numbers.length<=3104
  • 1000 <= numbers[i] <= 1000
  • numbers 按 非递减顺序 排列
  • 1000 <= target <= 1000
  • 仅存在一个有效答案

利用双指针对数组进行遍历,时间复杂度O(n),空间复杂度O(1)。

#include <vector>

using namespace std;

class Solution
{
public:
    vector<int> twoSum(vector<int> &numbers, int target)
    {
        int idxFront = 0, idxBack = numbers.size() - 1;
        while (idxFront < idxBack)
        {
            if (numbers[idxFront] + numbers[idxBack] < target)
            {
                idxFront++;
            }
            else if (numbers[idxFront] + numbers[idxBack] > target)
            {
                idxBack--;
            }
            else
            {
                break;
            }
        }
        return {idxFront + 1, idxBack + 1};
    }
};

209. 长度最小的子数组

给定一个含有 n 个正整数的数组和一个正整数 target 。

找出该数组中满足其总和大于等于 target 的长度最小的
子数组
[numsl, numsl+1, …, numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0。

示例 1:

输入:target = 7, nums = [2,3,1,2,4,3]
输出:2
解释:子数组 [4,3] 是该条件下的长度最小的子数组。

示例 2:

输入:target = 4, nums = [1,4,4]
输出:1

示例 3:

输入:target = 11, nums = [1,1,1,1,1,1,1,1]
输出:0

提示:

1 < = t a r g e t < = 1 0 9 1 <= target <= 10^9 1<=target<=109
1 < = n u m s . l e n g t h < = 1 0 5 1 <= nums.length <= 10^5 1<=nums.length<=105
1 < = n u m s [ i ] < = 1 0 5 1 <= nums[i] <= 10^5 1<=nums[i]<=105

进阶:

如果你已经实现 O(n) 时间复杂度的解法, 请尝试设计一个 O(n log(n)) 时间复杂度的解法。

最直观的解题方法就是滑动窗口,加左右快慢指针(可能有些不太准确)。

#include <vector>

using namespace std;

class Solution
{
public:
    int minSubArrayLen(int target, vector<int> &nums)
    {
        int sum = nums[0], idxSlow = 0, idxFast = 0, res = 0;
        while (idxFast < nums.size())
        {
            if (sum < target)
            {
                idxFast++;
                if (idxFast >= nums.size())
                    break;

                sum += nums[idxFast];
            }
            else
            {
                res = res == 0 ? idxFast - idxSlow + 1 : min(res, idxFast - idxSlow + 1);
                if (idxSlow < idxFast)
                {
                    sum -= nums[idxSlow];
                    idxSlow++;
                }
                else
                {
                    idxSlow++;
                    idxFast++;
                    if (idxFast >= nums.size())
                        break;
                    sum = nums[idxFast];
                }
            }
        }
        return res;
    }
};

除此之外,题解还有前缀和+二分查找等方法,但时间复杂度为 O ( n × l o g n ) O(n\times logn) O(n×logn),题解https://leetcode.cn/problems/minimum-size-subarray-sum/solutions/305704/chang-du-zui-xiao-de-zi-shu-zu-by-leetcode-solutio/?envType=study-plan-v2&envId=top-interview-150有写,在此不再赘述。

30. 串联所有单词的子串

给定一个字符串 s 和一个字符串数组 words。 words 中所有字符串 长度相同。

s 中的 串联子串 是指一个包含 words 中所有字符串以任意顺序排列连接起来的子串。

例如,如果 words = [“ab”,“cd”,“ef”], 那么 “abcdef”, “abefcd”,“cdabef”, “cdefab”,“efabcd”, 和 “efcdab” 都是串联子串。 “acdbef” 不是串联子串,因为他不是任何 words 排列的连接。
返回所有串联子串在 s 中的开始索引。你可以以 任意顺序 返回答案。

示例 1:

输入:s = “barfoothefoobarman”, words = [“foo”,“bar”]
输出:[0,9]
解释:因为 words.length == 2 同时 words[i].length == 3,连接的子字符串的长度必须为 6。
子串 “barfoo” 开始位置是 0。它是 words 中以 [“bar”,“foo”] 顺序排列的连接。
子串 “foobar” 开始位置是 9。它是 words 中以 [“foo”,“bar”] 顺序排列的连接。
输出顺序无关紧要。返回 [9,0] 也是可以的。

示例 2:

输入:s = “wordgoodgoodgoodbestword”, words = [“word”,“good”,“best”,“word”]
输出:[]
解释:因为 words.length == 4 并且 words[i].length == 4,所以串联子串的长度必须为 16。
s 中没有子串长度为 16 并且等于 words 的任何顺序排列的连接。
所以我们返回一个空数组。

示例 3:

输入:s = “barfoofoobarthefoobarman”, words = [“bar”,“foo”,“the”]
输出:[6,9,12]
解释:因为 words.length == 3 并且 words[i].length == 3,所以串联子串的长度必须为 9。
子串 “foobarthe” 开始位置是 6。它是 words 中以 [“foo”,“bar”,“the”] 顺序排列的连接。
子串 “barthefoo” 开始位置是 9。它是 words 中以 [“bar”,“the”,“foo”] 顺序排列的连接。
子串 “thefoobar” 开始位置是 12。它是 words 中以 [“the”,“foo”,“bar”] 顺序排列的连接。

提示:

1 < = s . l e n g t h < = 1 0 4 1 <= s.length <= 10^4 1<=s.length<=104
1 < = w o r d s . l e n g t h < = 5000 1 <= words.length <= 5000 1<=words.length<=5000
1 < = w o r d s [ i ] . l e n g t h < = 30 1 <= words[i].length <= 30 1<=words[i].length<=30
words[i] 和 s 由小写英文字母组成

主要参考了题解的解法:https://leetcode.cn/problems/substring-with-concatenation-of-all-words/solutions/1616997/chuan-lian-suo-you-dan-ci-de-zi-chuan-by-244a/?envType=study-plan-v2&envId=top-interview-150

代码如下:

#include <string>
#include <vector>
#include <unordered_map>

using namespace std;

class Solution
{
public:
    vector<int> findSubstring(string s, vector<string> &words)
    {
        if (words.size() == 0)
            return {};
        vector<int> res;
        // 单词的长度,滑动窗口移动步长
        int steps = words[0].size();
        // 单词的总长度
        int totalLen = steps * words.size();
        /*
         窗口的起始位置,一共有steps种情况,针对每一种情况,再去以steps
         为步长去移动窗口,这种做法是为了减少重复计算
        */
        for (int i = 0; i < steps && i + totalLen - 1 < s.size(); i++)
        {
            unordered_map<string, int> wordCnt;
            // 扩展窗口
            for (int j = 0; j < words.size(); j++)
            {
                wordCnt[s.substr(i + j * steps, steps)]++;
            }
            // 判断是否符合条件:如果符合条件,当前窗口与words中的单词刚好抵消,wordCnt为空
            for (int j = 0; j < words.size(); j++)
            {
                if (--wordCnt[words[j]] == 0)
                {
                    wordCnt.erase(words[j]);
                }
            }
            if (wordCnt.empty())
            {
                res.push_back(i);
            }
            // 开始滑动窗口
            for (int j = i + steps; j + totalLen - 1 < s.size(); j += steps)
            {
                string word = s.substr(j + totalLen - steps, steps);
                if (++wordCnt[word] == 0)
                {
                    wordCnt.erase(word);
                }
                word = s.substr(j - steps, steps);
                if (--wordCnt[word] == 0)
                {
                    wordCnt.erase(word);
                }
                if (wordCnt.empty())
                {
                    res.push_back(j);
                }
            }
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cherries Man

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值