在给定字符串中的特定位置添加空格后生成字符串

data structurec++server side programming

在此问题中,我们需要在字符串中给定的索引前添加空格。我们可以使用两种不同的方法来解决这个问题。第一种方法是移动给定字符串的字符以在特定索引处添加空格,第二种方法用空格替换预初始化字符串的字符。

问题描述− 我们给出了长度为 N 的字符串 str,其中包含字母数字字符。此外,我们给出了 spaceList 数组,其中包含 M 个表示字符串索引的正整数。我们需要在数组中存在的每个索引之前的字符串上应用空格。之后,我们需要打印更新后的字符串。

示例

输入

str = "welcometotutorialspoint", spaceList = {7, 9}

输出

'welcome to tutorialspoint'

解释 − 在这里,我们考虑基于 0 的索引。我们在输入字符串的第 7 个和第 9 个索引前添加了空格。

输入

str = "abc", spaceList = {1, 2}

输出

'a b c'

说明 − 我们在索引 1 和 2 前添加了空格。

输入

str = "IloveCProgramming", spaceList = {1, 5, 6}

输出

我喜欢 C 编程

解释 − 我们通过在给定索引处添加空格来分隔字符串。

方法 1

在这种方法中,我们将从数组中获取特定索引。之后,我们将在字符串末尾添加空格,并将所有字符向右移动 1,从当前索引开始到字符串末尾。

算法

步骤 1 - 用字符串的大小初始化 size 变量。

步骤 2 - 使用循环遍历字符串。

步骤 3 - 从 spaceList 数组中获取索引。

步骤 4 - 在给定字符串的末尾附加空格。

步骤 5 - 将所有 str[i+1] 字符替换为 str[i]。这里'I'从'strLen'开始,直到等于索引-1。

步骤6- 为str[index-1]分配空间。

步骤7- 最后,返回str,它是一个更新的字符串。

Example

#include <bits/stdc++.h>
using namespace std;

string AddSpaces(string str, vector<int> &spaceList) {
    // 获取列表的大小
    int size = spaceList.size();
    // 遍历空间列表
    while (size--) {
        // 获取索引以添加空间
        int index = spaceList[size] + 1;
        int strLen = str.size() - 1;
        // 在末尾附加空间
        str += ' ';
        // 移动空间
        for (int i = strLen; i >= index - 1; i--) {
            str[i + 1] = str[i];
        }
        str[index - 1] = ' ';
    }
    return str;
}
int main() {
    string str = "welcometotutorialspoint";
    vector<int> spaceList = {7, 9};
    cout << "The updated string is : " << AddSpaces(str, spaceList) << endl;
    return 0;
}

输出

The updated string is : welcome to tutorialspoint

时间复杂度− O(N*K),其中 K 是列表的大小,N 是字符串的大小。

空间复杂度− O(1),因为我们修改的是同一个字符串。

方法 2

在这种方法中,我们初始化包含总空格数等于字符串长度 + 列表长度的字符串。之后,我们用输入字符串的字符替换字符串来更新字符串,如果需要添加空格,则保留原样。

算法

步骤 1 − 用空字符串初始化"finalStr"字符串。此外,字符串长度应等于 str_size 和 list_size。这里,str_size 是字符串的大小,list_size 是列表的大小。

步骤 2 − 遍历 finalStr 字符串。

步骤 3 − 如果 l_index 小于列表大小,并且 p 等于 spaceList[l_index] + l_index,则将 l_index 增加 1,因为我们需要在该位置添加空间。

步骤 4 − 否则,将 str[index] 分配给 finalStr[p],并将索引的值增加 1。

步骤 5 − 返回"finalStr"字符串。

示例

#include <bits/stdc++.h>
using namespace std;

string AddSpaces(string str, vector<int> &spaceList) {
    int str_size = str.size(), list_size = spaceList.size(), l_index = 0, s_index = 0;
    string finalStr(str_size + list_size, ' ');
    // 遍历 M+N 长度
    for (int p = 0; p < str_size + list_size; p++) {
        if (l_index < list_size and p == spaceList[l_index] + l_index)
        l_index++;
        else
        finalStr[p] = str[s_index++];
    }
    // 返回所需字符串
    return finalStr;
}
int main() {
    string str = "welcometotutorialspoint";
    vector<int> spaceList = {7, 9};
    cout << "更新后的字符串为 : " << AddSpaces(str, spaceList) << endl;
    return 0;
}

输出

更新后的字符串为:welcome to tutorialspoint

时间复杂度− O(N + K),因为我们同时遍历列表和字符串。

空间复杂度− O(N + K),因为我们用空格初始化 finalStr。

第二种解决方案在时间复杂度方面更加优化,因为它同时遍历列表和字符串。第一种方法遍历列表的每个元素的字符串。程序员还可以尝试在字符串索引之后而不是在字符串索引之前插入空格。


相关文章