Shuffle String leetcode solution in cpp

The following is a C++ solution for the "Shuffle String" problem on LeetCode, along with explanations for each step:

#include <vector>
#include <string>

using namespace std;

string restoreString(string s, vector<int>& indices) {
    int n = s.length();
    string result(n, ' '); // Create a string of size n with all spaces

    for (int i = 0; i < n; i++) {
        result[indices[i]] = s[i]; // Place each character from s at the correct index in result
    }

    return result;
}

Step 1: Include the necessary header files for using vectors and strings in C++.

#include <vector>
#include <string>

Step 2: Use the using keyword to declare that we will be using the std namespace, which contains the definitions for vectors and strings in the C++ standard library.

using namespace std;

Step 3: Define the function restoreString that takes a string s and a vector of integers indices as parameters and returns a string.

string restoreString(string s, vector<int>& indices) {
    // Function code goes here
}

Step 4: Get the length of the input string s using the length function and store it in the variable n.

int n = s.length();

Step 5: Create a string result of size n and initialize it with all spaces using the constructor that takes a size and a character as arguments.

string result(n, ' ');

Step 6: Use a loop to iterate over each character in the input string s.

for (int i = 0; i < n; i++) {
    // Loop code goes here
}

Step 7: On each iteration of the loop, access the i-th character of the input string s and place it at the index given by indices[i] in the result string.

result[indices[i]] = s[i];

Step 8: After the loop is finished, the result string will contain the characters from the input string s shuffled according to the indices in the indices vector.

Step 9: Return the result string as the output of the function.

return result;

The restoreString function takes the original string s and an array of indices indices as inputs. It creates an empty string result of the same length as s and uses a loop to iterate over each character in s. On each iteration, it places the character at the correct index in result according to the corresponding index in indices. Finally, it returns the shuffled string result as the output.